简体   繁体   中英

TypeScript generic rest parameters to union return type

Currently, TypeScript allows declaring dynamic generic parameters.

function bind<U extends any[]>(...args: U);

But what if I want my function to return a union of argument types? Something like:

function bind<U extends any[]>(...args: U): U1 | U2 | U3...;

Is there a way to do that?

To get a union of all arguments you can use U[number] :

function bind<U extends any[]>(...args: U): U[number] {
    return args[Math.round(Math.random()*(args.length - 1))]; // dummy implementation
}
let r = bind(1,"2", true) // number | string | boolean
console.log(r)

You can also get the type at a certain position, but since we don't know if the position will exist we need to use a conditional type;

type At<T extends any[], I extends number> = T extends Record<I, infer U> ? U : never;
function bind<U extends any[]>(...args: U): At<U, 0> {
    return args[Math.round(Math.random()*(args.length - 1))]; // dummy implementation
}
let r = bind(1,"2", true) // number

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM