我想要一个与每个联合类型的单一类型都匹配的类型,但不匹配那些单一类型的任何联合

时间:2020-05-30 19:56:07

标签: typescript types typeclass typescript-generics type-systems

假设我定义了以下类型:

type A = {a:number};
type B = {a:string};
type C = {a:boolean};

type All = A | B | C;

现在,我想定义行为如下的通用类型S(不使用定义中的任何类型ABC

var a: S<A>;  // a is actually of type A
var b: S<B>;  // b is of type B
var c: S<C>;  // c is of type C
var all: S<All>; // all is of type never

要实现这一点,我可以这样定义S

type S<T> = All extends T ? never : T;

但这对我来说还不够,因为我也想要

var ab: S<A|B>; // ab should be type never but actually is A|B
var bc: S<B|C>; // bc should be type never but actually is B|C
var ca: S<C|A>; // ca should be type never but actually is C|A

问题

给出某种联合类型,如何定义可以与联合类型的每个单个组成部分匹配但不能与这些组成部分的任何联合匹配的泛型?

解决方案也应适用于具有三个以上组成部分的联合类型。

1 个答案:

答案 0 :(得分:0)

看来这正是我想要的:

type S<T> = [T] extends (T extends All ? [T] : never) ? T : never;