0

Suppose we have some concrete types A, B, C, etc. Also we have a wrapper type: Wrapper<T> where T could be any types e.g. A, B.

I need a variadic function that takes some Wrapper<T>s and returns the wrapped values as a tuple: [].

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

In this example result should be of type [A, B, C]. I don't know how to write the type of myFunction. Can you help?

2 Answers 2

1

this can be done with a tuple type

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, {});

here is Playground

Sign up to request clarification or add additional context in comments.

2 Comments

What if you want the arguments to be functions that provide a T? For example, something like function foo<T extends any[]>(...args: (bar: Bar) => T): T { return args; } Is this possible?
To clarify, I would then want the return type of foo((bar: Bar) => string, (bar: Bar) => number) to be [string, number] (and not [(bar: Bar) => string, (bar: Bar) => number)])
0

If you have a rough idea of how many wrapped arguments you want to pass to your functions, the simples option is to use a set of overloads. Something like this

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.