Typescript 检查字符串是否为联合类型的成员
为了避免类型转换,我想了解何时可以安全地确定给定值的类型。我可以使用以下字符串枚举执行此操作:Typescript 检查字符串是否为联合类型的成员,typescript,Typescript,为了避免类型转换,我想了解何时可以安全地确定给定值的类型。我可以使用以下字符串枚举执行此操作: enum Category { circle = "circle", square = "square", } const isObjValue = (val: any, obj: any) => Object.values(obj).includes(val) isObjValue('circle', Category) // tru
enum Category {
circle = "circle",
square = "square",
}
const isObjValue = (val: any, obj: any) => Object.values(obj).includes(val)
isObjValue('circle', Category) // true
但是我如何使用字符串联合呢
const Category = "circle" | "square"
const isValidCategory = (string) => {
if (/* string is in Category */) {
return string as Category
}
}
还在学习TS 如果有动态值,可以创建一个,以缩小该值的类型
type Category = "circle" | "square"
// User-defined type guard that narrows the s from string type
// to Category type if s is either "circle" or "square".
function isCategory(s: string): s is Category {
return s === "circle" || s === "square"
}
const a: string = "some dynamic string"
if (isCategory(a)) {
// a type here is Category
console.log(a, "is Category")
} else {
// a type here is string
console.log(a, "is not Category")
}
我担心它会涉及这么多类型(没有双关语),您可以从数组中创建类别类型,并在
isCategory
函数中使用该数组的方法.includes()
。但是如果你没有一大堆的价值观,我想这只会让事情变得更复杂。。。更喜欢简单易读的代码,而不是复杂简洁的代码。