打字稿:检查类型中是否包含值 [英] Typescript: check if value is contained in type

查看:24
本文介绍了打字稿:检查类型中是否包含值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在定义类型和检查该类型中是否包含值时遇到问题.

这是我的例子:

这些是类型:

导出类型 Key = 'features' |'特别的';导出类型 TabTypes = 'info' |'特点' |'特别' |'星星';

当用户更改选项卡时,它会发送来自 TabTypes 类型的字符串值.

activeTabChanged(事件:TabTypes){this.activeTab:TabTypes = 事件;//它不会让我在这里设置键,因为键的类型不同//但发送事件可以包含在 Key 类型中//如何检查来自 TabTypes 类型的发送事件是否包含在 Key 类型中this.key: 键 = 事件;}

是否有一种打字稿方法来检查具有类型的发送值是否可以等于来自不同类型的值?

解决方案

2019 解决方案:

我有同样的需求,并在另一个线程中找到了一种更简单的方法.总之,帕特里克·罗伯茨在该链接中所说的(用这个问题值更新)是:

<块引用>

不要过度复杂化.

function isOfTypeTabs (keyInput: string): keyInput is TabTypes {返回 ['info', 'features', 'special', 'stars'].includes(keyInput);}

<块引用>

参见打字稿中的`is`关键字有什么作用? 了解我们为什么不只使用 boolean 返回类型的更多信息.

信用和完整来源:https://stackoverflow.com/a/57065680/6080254

I have problem with defined types and checking if a value is contained in that type.

Here is my example:

these are the types:

export type Key = 'features' | 'special';

export type TabTypes = 'info' | 'features' | 'special' | 'stars';

when the user changes a tab, it sends a string value from 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;
}

is there a typescript way to check if a sent value with a type can equal a value from a different type?

解决方案

2019 Solution:

I had the same need and found an easier way to do that in another thread. In summary, what Patrick Roberts says in that link (updated with this question values) is:

Don't over-complicate it.

function isOfTypeTabs (keyInput: string): keyInput is TabTypes {
  return ['info', 'features', 'special', 'stars'].includes(keyInput);
}

See What does the `is` keyword do in typescript? for more information on why we don't just use a boolean return type.

Credits and full source here: https://stackoverflow.com/a/57065680/6080254

这篇关于打字稿:检查类型中是否包含值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆