简体   繁体   English

TypeScript通用休息参数以联合返回类型

[英]TypeScript generic rest parameters to union return type

Currently, TypeScript allows declaring dynamic generic parameters. 当前,TypeScript允许声明动态通用参数。

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] : 要获得所有参数的并集,可以使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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