Typescript: Obtain the type parameters of a function with all declarations

时间:2019-04-23 15:11:09

标签: typescript typescript-typings

I'm trying to get an array of type parameters of a function with all the declarations (Overloads) with or concatenation.

For example, I can use the Parameters<T> but this function only get the last declaration.

interface FOO {
    foo(a: string, b: string): string;
    foo(a: boolean, b: string): string;
    foo(a: boolean, b:string, c: number): string;
};

type params = Parameters<FOO["foo"]>; // [boolean, string, number]

Actually, the params type is [boolean, string, number] but I expect the type as [string, string] | [boolean, string] | [boolean, string, number].

1 个答案:

答案 0 :(得分:2)

TS不支持从重载函数推断联合参数类型。 TS函数重载的工作方式就像切换情况一样,最终会崩溃为签名之一。选中此section

  

从具有多个调用签名的类型(例如重载函数的类型)进行推断时,将根据最后一个签名(可能是最宽松的情况)进行推断。无法基于参数类型列表执行重载解析。

如果此类参数类型对您很重要,则可以添加:

interface FOO {
    foo(a: string, b: string): string;
    foo(a: boolean, b: string): string;
    foo(a: boolean, b: string, c: number): string;
    foo(...args: [string, string] | [boolean, string] | [boolean, string, number]): string;
};

编辑:好的,我错了。事实证明,即使Titian正式宣称“不可能”,TS向导也总是会找到方法。确保检查出他的brilliant answer