假设我定义了以下类型:
type A = {a:number};
type B = {a:string};
type C = {a:boolean};
type All = A | B | C;
现在我要定义通用类型S
(不使用定义中的任何类型A
,B
和C
):
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
问题
给出某种联合类型,如何定义可以与联合类型的每个单个组成部分匹配但不能与这些组成部分的任何联合匹配的泛型?
解决方案也应适用于具有三个以上组成部分的联合类型。
假设我定义了以下类型:type A = {a:number};类型B = {a:string};类型C = {a:boolean};输入All = A | B | C;现在,我要定义通用类型S(不使用任何类型A,...
似乎这正是我想要的: