打字稿中有没有办法说“ include” (排除)?
我有一个像: 键入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 typetype 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有一个实用程序类型与 <<<代码>排除&lt; t,u&gt; 实用程序类型:
请注意,没有什么可以迫使第二个参数(在此称为
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 theExclude<T, U>
utility type:Note that nothing forces the second argument (called
U
here) to eitherExtract<T, U>
orExclude<T, U>
to contain only elements from the first argument (calledT
here). Hence that'zzz'
above doesn't have an effect on anything.Playground link to code
双重“排除”可以充当。
首先,如果您使用排除,则创建要排除的所有项目的列表。
这将导致一组:
'Zeta'| 'beta'| '伽玛'| 'Mu'
我们可以将该集合不排除在内,以使我们还需要我们想要的值:
此结果在:
'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.
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:
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".