Anatole Lucet
Anatole Lucet

Reputation: 1813

Conditional type using a function param's typeof

I'm trying to do something like this:

const getParams = (
  cb: number | ((...args: any[]) => any)
): typeof cb extends number ? [] : Parameters<typeof cb> => { // Type 'number' is not assignable to type '(...args: any) => any'.
  return []
}

This function doesn't rally make any sens, but it's just a simple representation of my issue.

For some reason typescript doesn't take in count the extends condition. I'd like to know if there's a proper way to do this.

Upvotes: 0

Views: 31

Answers (1)

Aplet123
Aplet123

Reputation: 35512

The easiest way is probably to use functino overloading:

const getParams: {
  (cb: number): [],
  <T extends (...args: any[]) => any>(cb: T): Parameters<typeof cb>
} = (
  cb: number | Function
): any => {
  return []
}

Upvotes: 1

Related Questions