扩展参数中的打字稿函数泛型参数

时间:2021-06-05 08:32:13

标签: typescript generics typescript-generics conditional-types

我有以下功能:

type SomeType<T> = Record<string, T>;
declare function test<T>(...args: SomeType<T>[]): T;

我想这样称呼它(a 应该是 number|string 类型):

const a = test({a: 3}, {b: "as"});

但那样我得到一个错误:Type 'string' is not assignable to type 'number'. 我可以在不显式传递泛型参数 number|string 或使用条件类型的情况下完成这项工作吗?

Playground

1 个答案:

答案 0 :(得分:1)

可变元组可能有帮助:

declare function test<T extends any[]>(...args: [...T]): T;

const a = test({ a: 3 }, { b: "as" });