打字稿中有没有办法说“ include” (排除)?

发布于 2025-02-11 18:14:04 字数 259 浏览 2 评论 0原文

我有一个像: 键入alphabetlike ='a'| 'B'| 'C'| 'Zeta'| 'beta'| '伽玛'| 'Mu'; 我希望能够构建类型 类型Alphabet ='a'| 'B'| 'C'。我可以使用排除和删除Zeta,beta,伽马和MU来做到这一点,但是这是很多要删除的事情,如果将更多值添加到字母表中,它会更改字母。我想知道我的价值是否从该类型中删除了“ Alphabetlike”。

有没有办法进行包含而不是排除?

I have a String Union that looks like:
type AlphabetLike = 'a' | 'b' | 'c' | 'zeta' | 'beta' | 'gamma' | 'mu';
I want to be able to construct the type
type Alphabet = 'a' | 'b' | 'c'. I could do this by using Exclude and removing zeta, beta, gamma, and mu but that's a lot of things to remove and if more values are added to AlphabetLike, it changes Alphabet. I want to know if my value from "AlphabetLike" is ever removed from that type.

Is there a way to do an Include instead of an Exclude?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

柳絮泡泡 2025-02-18 18:14:04

有一个实用程序类型 <<<代码>排除&lt; t,u&gt; 实用程序类型

type AlphabetLike = 'a' | 'b' | 'c' | 'zeta' | 'beta' | 'gamma' | 'mu';

type Alphabet = Extract<AlphabetLike, 'a' | 'b' | 'c' | 'zzz'>;
// type Alphabet = "a" | "b" | "c"

请注意,没有什么可以迫使第二个参数(在此称为u)到extract&lt; t,t,u&gt; < /code>或排除&lt; t,u&gt;仅包含第一个参数中的元素(在此处称为t)。因此,上面的'zzz'对任何事物都没有影响。

Playgrounger链接到代码

There is an Extract<T, U> utility type which acts like the opposite of the Exclude<T, U> utility type:

type AlphabetLike = 'a' | 'b' | 'c' | 'zeta' | 'beta' | 'gamma' | 'mu';

type Alphabet = Extract<AlphabetLike, 'a' | 'b' | 'c' | 'zzz'>;
// type Alphabet = "a" | "b" | "c"

Note that nothing forces the second argument (called U here) to either Extract<T, U> or Exclude<T, U> to contain only elements from the first argument (called T here). Hence that 'zzz' above doesn't have an effect on anything.

Playground link to code

清音悠歌 2025-02-18 18:14:04

双重“排除”可以充当。

首先,如果您使用排除,则创建要排除的所有项目的列表。

type GreekAlphabet = Exclude<AlphabetLike, 'a' | 'b' | 'c'>

这将导致一组:
'Zeta'| 'beta'| '伽玛'| 'Mu'
我们可以将该集合不排除在内,以使我们还需要我们想要的值:

type Alphabet = Exclude<AlphabetLike, GreekAlphabet>

此结果在:
'a'| 'B'| 'C'
有效地包括&lt; alphabetlike,'a'|'b'|'c'&gt;,如果从“ alphabetlike”中删除了使用的选项,将保护您。

A double "exclude" can act as an include.

First, create a list of all of the items you want to exclude if you were using exclude.

type GreekAlphabet = Exclude<AlphabetLike, 'a' | 'b' | 'c'>

This results in a set that is:
'zeta' | 'beta' | 'gamma' | 'mu'
We can use that set with Exclude to give us back the values we want:

type Alphabet = Exclude<AlphabetLike, GreekAlphabet>

This results in:
'a' | 'b' | 'c'
which is effectively Include<AlphabetLike, 'a'|'b'|'c'> and will protect you if an option in use is removed from "AlphabetLike".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文