首页 > 解决方案 > 我希望有一个匹配每一种联合类型的类型,但不是这些单一类型的任何联合

问题描述

假设我定义了以下类型:

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

type All = A | B | C;

现在我想定义行为如下的泛型类型S(不使用任何类型AB并且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

问题

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

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

标签: typescripttypestypeclasstypescript-genericstype-systems

解决方案


看来这正是我想要的:

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

推荐阅读