接受泛型类型作为输入参数的可变参数泛型函数

时间:2020-06-01 09:42:06

标签: typescript typescript-generics

假设我们有一些具体的类型ABC等。另外,我们还有一个包装类型:Wrapper<T>,其中T可以是任意类型类型,例如AB

我需要一个可变参数函数,该函数需要一些Wrapper<T>并将包装的值作为元组返回:[]

let wa: Wrapper<A>;
let wb: Wrapper<B>;
let wc: Wrapper<C>;
let result = myFunction(wa, wb, wc);

在此示例中,result的类型应为[A, B, C]。我不知道如何写myFunction的类型。你能帮忙吗?

2 个答案:

答案 0 :(得分:0)

如果您对要传递给函数的包装参数有个粗略的了解,那么simples选项就是使用一组重载。像这样

type Wrapper<T> = {
    type: T
}

type A = number
type B = boolean
type C = string

function f<A, B, C>(w1: Wrapper<A>, w2: Wrapper<B>, w3: Wrapper<C>): [A, B, C]
function f<A, B>(w1: Wrapper<A>, w2: Wrapper<B>): [A, B]
function f<A>(w1: Wrapper<A>): [A]
function f(...ws: Wrapper<any>[]): any[] {
    return ws.map(w => w.type)
}

declare const a: Wrapper<A>
declare const b: Wrapper<B>
declare const c: Wrapper<C>

const foo = f(a, b, c) // [A, B, C]

答案 1 :(得分:0)

这可以通过元组类型完成

function foo<T extends any[]>(...args: T): T {
    return args;
}
// you dont need to pass generic parameters ofc. typescript will infer same type anyway
// return type of this function is now [string, number, object]
foo<[string, number, object]>("a", 1, {});

这里是Playground