简体   繁体   中英

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> . (Sort of the opposite of #14107 and #16644

Edit : I've discovered the following pattern when K is a union of string literals:

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 . 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>;

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