TypeScript中Array.includes类型不兼容问题:求更优实现方案
TypeScript const数组的includes类型兼容问题
核心问题可简化为以下TypeScript代码,运行时会触发类型错误:
let arr = ["A","B"] as const // 必须为const/readonly function isAorB(str: string): str is "A" | "B" { return arr.includes(str); }
报错信息:Argument of type 'string' is not assignable to parameter of type "A" | "B"
现有几种解决方案,但均存在不合理之处:
方案1:缩小str的类型
let arr = ["A", "B"] as const; function isAorB(str: string): str is "A" | "B" { return arr.includes(str as "A" | "B"); }该方案通过类型断言强制将
str标记为"A"|"B",但这与实际传入的string类型不符,属于欺骗编译器的行为。方案2:使用Set
const arrSet = new Set(["A", "B"] as const); function isAorB(str: string): str is "A" | "B" { return arrSet.has(str); }该方案属于过度设计,明明用
includes即可实现需求,无需额外创建Set对象。方案3:放宽数组类型
let arr = ["A", "B"] as const; function isAorB(str: string): str is "A" | "B" { return (arr as readonly string[]).includes(str); }该方案将
arr转为readonly string[],虽然放宽了includes的参数类型要求,但牺牲了数组本身的类型安全性,并非合理选择。
请问是否存在无需欺骗编译器或创建新对象的实现方式?
内容的提问来源于stack exchange,提问作者Yorai Levi
相关产品推荐
相关产品推荐

