【问题标题】:TypeScript: Define a type by inferring a Function's Argument TypesTypeScript:通过推断函数的参数类型来定义类型
【发布时间】:2019-12-17 21:54:07
【问题描述】:

是否有可能描述由函数参数推断的类型?我需要这样的东西:

// some fn I have no control over its params
function someFn(a: string, b?: number, c?: any): any { /* ... */ }

// my wanted type that describes the args as object-records:
const result: MyType<typeof someFn> = {
 a: 'str',
 b: 42,
 c: null
};

我无法控制函数参数的签名,因此无法将其转换为 someFn(args: SomeFnArgs) 和 MyType&lt;SomeFnArgs&gt;。

我什至不知道是否可以描述类型。

【问题讨论】:

    标签: typescript typescript-typings typescript-generics


    【解决方案1】:

    是的,虽然不完全是那样。键入函数签名时,参数的名称会丢失。在您的示例中,someFn 的参数类型是 [string, number?, any](尽管该示例不太有效,因为非可选参数可能不会出现在可选参数之后。

    你可以用这个(playground)得到这个类型:

    // type Parameters<T extends Function> = T extends (...args: infer R) => any ? R : never;
    // How it's implemented, Parameters is a built-in type.
    
    function someFn(a: string, b?: number, c?: any): any { /* ... */ }
    
    type T0 = Parameters<typeof someFn>; // type T0 = [string, (number | undefined)?, any?]
    
    const x: T0 = ['hello', 42]; // good
    const y: T0 = ['hello', 'world', '!!']; // bad
    

    【讨论】:

    • 谢谢,我错过了c 参数之后的?。我知道有一个包含镜像类型的数组的可能性。不幸的是,这还不够,我还想获取给定的名称,但我认为这是不可能的,那么?
    • @jlang 除非您将自己限制为具有单个对象参数 (function foo({bar, baz}) {}) 的函数,否则恐怕不会。
    • @MadaraUchiha 您也可以为此使用内置类型 Parameters。 type T1 = Parameters&lt;typeof someFn&gt;
    猜你喜欢
    • 2019-04-26
    • 2018-08-28
    • 2016-11-01
    • 2016-12-05
    • 2021-11-01
    • 2020-01-23
    • 1970-01-01
    • 2021-12-22
    • 2020-07-10
    相关资源
    最近更新 更多