是否可以在typescript中区分字符串和字符串枚举?
所以我有是否可以在typescript中区分字符串和字符串枚举?,typescript,Typescript,所以我有 type newType = ResourcesKey | string; enum ResourcesKey { FirstString= 'path', ... } 然后我有一个函数来获取这个实例,我想测试它是一个字符串还是一个枚举,但是在typescript中,这两个被认为是相同的吗 Function(instance: newType) { if (instance instanceof ResourcesKey) { } }
type newType = ResourcesKey | string;
enum ResourcesKey {
FirstString= 'path',
...
}
然后我有一个函数来获取这个实例,我想测试它是一个字符串还是一个枚举,但是在typescript中,这两个被认为是相同的吗
Function(instance: newType)
{
if (instance instanceof ResourcesKey) {
}
}
这将返回一个错误
错误TS2359:“instanceof”表达式的右侧必须是“any”类型或可分配给“Function”接口类型的类型
我能做些什么来比较实例和枚举的类型吗
例如,在C#中,我可能会做类似的事情
if (typeof (instance) == ResourcesKey) {
}
当然,我可以解决这个问题,但我想知道首选的做法是什么
instanceof
无论如何只适用于类,所以不能将其用于枚举
运行时枚举只是字符串,因此测试这意味着实际测试字符串值是否在枚举中。您可以创建一个自定义typeguard来执行检查并通知编译器类型:
type newType = ResourcesKey | string;
enum ResourcesKey {
FirstString = 'path',
}
function isResourceKey(o: newType): o is ResourcesKey {
return Object.keys(ResourcesKey).some(k => ResourcesKey[k as keyof typeof ResourcesKey] === o);
}
function doStuff(instance: newType) {
if (isResourceKey(instance)) {
console.log(`Res: ${instance}`) // instance: ResourcesKey
} else {
console.log(`Str: ${instance}`) // instance: string
}
}
doStuff("")
doStuff(ResourcesKey.FirstString)
doStuff("path") // still resource
不,这里枚举值只是字符串。如果要检查
instance
是否是枚举值之一,可以使用类似Object.values(ResourcesKey).includes(instance)
instanceof也不起作用吗?它不应该检查实例在实例的原型链中是否具有字符串构造函数的prototype属性吗?您应该看看传输代码(javascript)。运行时枚举值是常规字符串