bbbryan14
bbbryan14

Reputation: 165

Typescript function signature incorrect when method is from an object

Has anyone ran into this issue when you get a method from an object, the function signature is not correct?

interface Fruits {
  shape: string
  size: number
}

interface Vegetable {
  color: string
  weight: number
}

const Foo = {
  fruit: (param: Fruit) => param,
  veggie: (param: Vegetable) => param
}

const bar = (key: keyof typeof Foo) => {
  return Foo[key]
}

const baz = bar('veggie')
//  inspect baz and it will give you a union type

const quz = baz({color: 'red', weight: 10})
//  the param type refers back to fruit

Upvotes: 0

Views: 95

Answers (1)

bbbryan14
bbbryan14

Reputation: 165

I'm an idiot, the solution is

const bar = <T extends keyof typeof Foo>(key: T) => {
  return Foo[key]
}

and typescript will get the type correctly

Upvotes: 2

Related Questions