gpt4 book ai didi

typescript - 检查变量是否属于 Typescript 中的自定义类型

转载 作者:行者123 更新时间:2023-12-03 14:38:58 25 4
gpt4 key购买 nike

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

代码:

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;
}

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

最佳答案

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

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

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);
}

更详细的解释可以找到 here .

关于typescript - 检查变量是否属于 Typescript 中的自定义类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54147575/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com