typescript - 我希望有一个匹配每一种联合类型的类型,但不是这些单一类型的任何联合
问题描述
假设我定义了以下类型:
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
问题
给定一些联合类型,如何定义可以与联合类型的每个组成部分匹配但不能与这些组成部分的任何联合匹配的泛型类型?
解决方案也应该适用于具有 3 个以上成分的联合类型。
解决方案
看来这正是我想要的:
type S<T> = [T] extends (T extends All ? [T] : never) ? T : never;
推荐阅读
- php - 复制打开流失败:HTTP 请求失败!在 C:\wamp64\www\ 中找不到 HTTP/1.1 404
- python - 返回时出现UnboundLocalError:Python
- sql - 路径范围内的 sql 记录列表
- javascript - v-on:点击目标不在正确的元素中?
- vba - 为术语列表中的每个匹配项添加匹配的注释到 word 文档
- c# - C# WPF 文本框 GotFocus SelectAll 不起作用
- c# - 如何将球射到 Touch X 位置 Unity 3D?
- python - 如何在 Instant-veins-4.7.1-i1.ova 上运行 sumo-gui
- node.js - 浏览器一直“等待本地主机”
- node.js - 异步等待不适用于回调节点(没有承诺)