简体   繁体   English

打字稿中的参数化联合

[英]Parametric union in typescript

Is there a generic way of specifying a union parametrically? 是否存在以参数方式指定联合的通用方法? I'm looking for a way of generically specifying something like: 我正在寻找一种通用的指定方式:

type U<K> = T<K1> | T<K2> | ... | T<Kn> // Where K === (K1 | ... | Kn)

Note : I'm dealing with a case where T<U | V> !== T<U> | T<V> 注意 :我正在处理T<U | V> !== T<U> | T<V> T<U | V> !== T<U> | T<V> T<U | V> !== T<U> | T<V> . T<U | V> !== T<U> | T<V> (Sort of the opposite of #14107 and #16644 (排序与#14107#16644相反

Edit : I've discovered the following pattern when K is a union of string literals: 编辑 :当K是字符串文字的并集时,我发现了以下模式:

type U<K> = {[key in K]: T<key>}[K]

but doesn't play nicely with type inference if I try to use it as a function argument. 但如果我尝试将其用作函数参数,则不能很好地使用类型推断。

TypeScript 2.8 provides another way of accomplishing this distribution using conditional types . TypeScript 2.8提供了使用条件类型完成此分发的另一种方法。 An example from the release announcement: 发布公告中的一个例子:

type Foo<T> = T extends any ? T[] : never;

/**
 * Foo distributes on 'string | number' to the type
 *
 *    (string extends any ? string[] : never) |
 *    (number extends any ? number[] : never)
 * 
 * which boils down to
 *
 *    string[] | number[]
 */
type Bar = Foo<string | number>;

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

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