gpt4 book ai didi

不排除 Typescript 联合类型

转载 作者:行者123 更新时间:2023-12-04 14:05:55 26 4
gpt4 key购买 nike

我对联合类型和 Exclude ( playground link ) 有疑问:

type Foo = {
data: string;
otherData: number;
};
type Bar = Omit<Foo,'otherData'>
// type Bar = { data: string; }; // Even this is not working
type FooBar = Foo | Bar;

type ShouldBeFoo = Exclude<FooBar, Bar>; // Not working
// ShouldBeFoo = never

type ShouldBeBar = Exclude<FooBar, Foo>; // Somehow working
// ShouldBeBar = { data: string }

我是否遗漏了与联合类型和/或Exclude相关的内容?

我也尝试了 TS 4.4 和 4.2,结果相同。


注意:

我们使用类型保护发现了这个问题,您可以在 playground here 中看到它.

最佳答案

Exclude 排除匹配而非相等的类型。

您正在从 FooBar 中排除 BarBar 匹配 BarBar 匹配 Foo。所以你排除了两者。

你可以使用类似的东西

type ExcludeExact<T, U> = T extends U ? U extends T ? T : never : never

关于不排除 Typescript 联合类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68528249/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com