san*_*ooh 5 types typescript angular
我对定义的类型有疑问,并检查该类型中是否包含值。
这是我的示例:
这些类型是:
export type Key = 'features' | 'special';
export type TabTypes = 'info' | 'features' | 'special' | 'stars';
Run Code Online (Sandbox Code Playgroud)
当用户更改选项卡时,它会从Type of TabTypes发送一个字符串值。
activeTabChanged(event: TabTypes) {
this.activeTab: TabTypes = event;
// it won't let me set the key here because key has a different type
// but the send event can be contained in type Key
// how can I check if the send event from type TabTypes is contained in type Key
this.key: Key = event;
}
Run Code Online (Sandbox Code Playgroud)
有没有一种打字稿方法来检查带有类型的发送值是否可以等于来自其他类型的值?
Bru*_*iro 15
我有同样的需求,并在另一个线程中找到了一种更简单的方法。总之,帕特里克罗伯茨在该链接中所说的(用这个问题值更新)是:
不要把它复杂化。
function isOfTypeTabs (keyInput: string): keyInput is TabTypes {
return ['info', 'features', 'special', 'stars'].includes(keyInput);
}
Run Code Online (Sandbox Code Playgroud)
请参阅打字稿中的“is”关键字有什么作用?有关为什么我们不只使用
boolean返回类型的更多信息。
积分和完整来源:https : //stackoverflow.com/a/57065680/6080254
您可以使用字符串枚举。
export enum Keys = {
Features = 'features',
Special = 'special',
}
// Compare it
if (currentKey === Keys.Special) { console.log('Special key is set'); }
Run Code Online (Sandbox Code Playgroud)
为了检查您的值是否在预定义的枚举中定义,您可以执行以下操作:
if (currentKey in Keys) { console.log('valid key'); }
Run Code Online (Sandbox Code Playgroud)