使用字符串进行类型比较



这可能吗?或者有简单的方法来解决这个问题吗?

我想将字符串值与类型进行比较。我有一个如下所示的类型和一个从api请求传入的字符串值。

type stringTypes = 'abc' | 'asd'
const testVal = 'testVal'
if (testVal !== stringTypes) {
// throw error
}

我已经解决了如下问题,但我想知道是否还有其他选择。

type stringTypes = 'abc' | 'asd'
const testVal = 'testVal'
const controlArr: stringTypes[] = ['asd', 'abc']
if (!controlArr.includes(testVal)) {
// throw error
}

EDIT1:我可以使用枚举,但在typescript中枚举是不可扩展的。在我的情况下,我需要根据数据库模型扩展类型,如下所示。所以我需要比较字符串和类型。

type stringTypes = 'abc' | 'asd'
type channelTypes = stringTypes | 'foo' | 'bar'
type streamTypes = stringTypes | 'das' | 'xyz'
const testVal = 'testVal'
if (testVal !== stringTypes) {
// throw error
}

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

最新更新