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

问题描述 投票:0回答:1

假设我定义了以下类型:

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

问题

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

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

假设我定义了以下类型:type A = {a:number};类型B = {a:string};类型C = {a:boolean};输入All = A | B | C;现在,我要定义通用类型S(不使用任何类型A,...

typescript types typeclass typescript-generics type-systems
1个回答
0
投票

似乎这正是我想要的:

© www.soinside.com 2019 - 2024. All rights reserved.