[英]Type comparison with String
Is this possible or is there an easy way to solve this?这是可能的还是有一个简单的方法来解决这个问题?
I would like to compare a string value with a type.我想将字符串值与类型进行比较。 I have a type like below and a string value incoming from api request.我有一个像下面这样的类型和一个从 api 请求传入的字符串值。
type stringTypes = 'abc' | 'asd'
const testVal = 'testVal'
if (testVal !== stringTypes) {
// throw error
}
I have solved like below but I wondered if there' s another options.我已经解决了如下问题,但我想知道是否还有其他选择。
type stringTypes = 'abc' | 'asd'
const testVal = 'testVal'
const controlArr: stringTypes[] = ['asd', 'abc']
if (!controlArr.includes(testVal)) {
// throw error
}
TypeScript is just a compiler, so you can't iterate thought a type, but you could achieve what you want by using enum
type TypeScript 只是一个编译器,所以你不能迭代一个类型,但你可以通过使用enum
类型来实现你想要的
const testVal = 'testVal'
enum stringTypes {
'Abc' = 'abc',
'Dsd' = 'asd',
}
//Check if string is enum value
const isEnumValue = (value: string, enumType: any) => {
return Object.values(enumType).includes(value)
}
console.log(isEnumValue('abc', stringTypes)) //true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.