[英]is it possible to differentiate between string and enum of strings in typescript?
所以我有
type newType = ResourcesKey | string;
enum ResourcesKey {
FirstString= 'path',
...
}
然后,我有一个接受该实例的函数,我想测试它是字符串还是枚举,但是在打字稿中,这两者被视为相同吗?
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.