检查变量是否属于 Typescript 中的自定义类型 [英] Check if variable belongs to custom type in Typescript

查看:49
本文介绍了检查变量是否属于 Typescript 中的自定义类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查变量是否属于某种类型.

代码:

type GeneralType = SubTypeA |子类型B;type SubTypeA = 'type1' |'type2';type SubTypeB = 'type3' |'type4';函数 someFunction(arg1: GeneralType) {if (arg1 instanceof SubTypeA) {//做点什么}//继续函数返回 arg1;}

当然这段代码在第 6 行失败了,因为 instanceof 不能用于类型.有没有我可以使用的替代选项,而无需明确检查 SubTypeA 的每个可能值?

解决方案

正如评论中提到的,似乎没有直接的方法来实现这一点.

最后,我发现最优雅的方法是使用 Type Guards如下:

type GeneralType = SubTypeA |子类型B;type SubTypeA = 'type1' |'type2';type SubTypeB = 'type3' |'type4';函数 someFunction(arg1: GeneralType) {如果(isSubTypeA(arg1)){//做点什么}//继续函数}function isSubTypeA(arg: GeneralType): arg is SubTypeA {return ['type1', 'type2'].some(element => element === arg);}

可以在此处找到更详细的说明.>

I'm trying to check whether a variable belongs to a certain type or not.

Code:

type GeneralType = SubTypeA | SubTypeB;
type SubTypeA = 'type1' | 'type2';
type SubTypeB = 'type3' | 'type4';

function someFunction(arg1: GeneralType) {
  if (arg1 instanceof SubTypeA) {
    // Do something
  }
  // Continue function
  return arg1;
}

Of course this code fails in line 6 because instanceof is not usable for types. Is there an alternative option I could use without needing to check explicitly every posible value for SubTypeA?

解决方案

As mentioned in the comments, it seems there's no strightforward method to achieve this.

Finally, the most elegant way I found to do it is using Type Guards as follows:

type GeneralType = SubTypeA | SubTypeB;
type SubTypeA = 'type1' | 'type2';
type SubTypeB = 'type3' | 'type4';

function someFunction(arg1: GeneralType) {
  if (isSubTypeA(arg1)) {
    // Do something
  }
  // Continue function
}

function isSubTypeA(arg: GeneralType): arg is SubTypeA {
  return ['type1', 'type2'].some(element => element === arg);
}

A more detailed explanation can be found here.

这篇关于检查变量是否属于 Typescript 中的自定义类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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