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

dlaberge picture dlaberge  路  3Comments

siddjain picture siddjain  路  3Comments

seanzer picture seanzer  路  3Comments

uber5001 picture uber5001  路  3Comments

jbondc picture jbondc  路  3Comments