Typescript: Infering passed type of function argument?

Created on 9 Dec 2019  路  2Comments  路  Source: microsoft/TypeScript

const a = (a: string) => { }

const b = (...args: Parameters<typeof a>) {
}

// TS says x is any here, that's why it doesn't work as expected
const c = (x) => (...args: Parameters<typeof x>) => {
}

const d = <T>(...args: Parameters<T>) => {
}

// works:
b()

// doesnt work. i would like to get this working
c(a)(1)

// dont want this solution
d<typeof a>(1)

Most helpful comment

x is any because you're not explicitly giving it a type. If you want behavior where the next function call infers its argument type based on the previous, then you can do something like:

const c = <T extends (...args: any[]) => any>(x: T) => (...args: Parameters<T>) => {}

and then when you put in c(a) typescript infers the next function as (a: string) => void

All 2 comments

x is any because you're not explicitly giving it a type. If you want behavior where the next function call infers its argument type based on the previous, then you can do something like:

const c = <T extends (...args: any[]) => any>(x: T) => (...args: Parameters<T>) => {}

and then when you put in c(a) typescript infers the next function as (a: string) => void

Wow you are genius! it really works! thanks you !!!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rbuckton picture rbuckton  路  139Comments

chanon picture chanon  路  138Comments

Gaelan picture Gaelan  路  231Comments

quantuminformation picture quantuminformation  路  273Comments

xealot picture xealot  路  150Comments