简体   繁体   中英

Typescript: Infer function argument

Ever Since TS 2.8, we can do the following:

type ArgType<F> = F extends (a: infer A) => any ? A : any

const fn: (s: string) => 500

ArgType<(typeof fn> // => string

Let's assume the following situation.

type FunctionCollection = {
  [key: string]: (s: ???) => any
}

const fnCol: FunctionCollection = {
    someFn: (s: string) => 500
}

Question: Is there any way to replace ??? (or the whole of FunctionCollection) with a type such that

ArgType<(typeof fnCol)["someFn"]> 'equals' string

(The issue is that for example, if ??? = any , we get any )

Since the argument type can be different for each property of the type, you will need a type argument:

type FunctionCollection<T> = {
    [P in keyof T]: (s: T[P]) => any
}

Now to create such a variable you would need to specify the properties as the type argument to FunctionCollection which is less then ideal:

const fnColNoInference: FunctionCollection<{
    someFn: string;
    otherFn: number;
}> = {
    someFn: (s: string) => 500,
    otherFn: (s: number) => 500
}

A better approach is to use the inference behavior of functions to infer the type of the constant:

function functionCollection<T>(args: FunctionCollection<T>) {
    return args
}

const fnCol = functionCollection({
    someFn: (s: string) => 500,
    otherFn: (s: number) => 500
})

let d : ArgType<(typeof fnCol)["someFn"]> // is string 
let d2 : ArgType<(typeof fnCol)["otherFn"]> // is number

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM