简体   繁体   English

打字稿:推断函数参数

[英]Typescript: Infer function argument

Ever Since TS 2.8, we can do the following: 从TS 2.8开始,我们可以执行以下操作:

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 (或整个FunctionCollection)的类型

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

(The issue is that for example, if ??? = any , we get any ) (问题是,例如,如果??? = any ,我们得到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: 现在要创建这样的变量,您需要将属性指定为FunctionCollection的类型参数,这比理想情况要差:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从打字稿中的功能参数推断类型参数 - infer type argument from function argument in typescript TypeScript 推断函数第一个参数的第二个参数 - TypeScript infer second argument of a function first argument 通过 Typescript 中的其他 function 参数推断 function 参数的类型 - Infer type of function argument by other function argument in Typescript 为什么Typescript不能推断出这个函数的参数类型? - Why can't Typescript infer the argument types of this function? 为什么 Typescript 不能推断出可选 arguments 的 function 参数类型? - Why can't Typescript infer function argument types for optional arguments? 在这种情况下,TypeScript 能否根据参数推断出 function 返回类型? - Can TypeScript infer a function return type based on an argument in this scenario? Typescript function 作为参数 - 使用输入的 ZDBC11CAA5BDA28F77E6FB4EDABD8 推断 output 类型 - Typescript function as argument - infer output type using inputted arguments 通用接口内的 Typescript 函数来推断参数类型 - Typescript function inside generic interface to infer argument type 从TypeScript中的函数的参数类型推断通用类型参数 - Infer generic type argument from parameter type of function in TypeScript 在TypeScript中推断接口类型参数 - Infer interface type argument in TypeScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM