我所遇到的问题可以归结为以下错误的打字稿代码,
let arr = ["A","B"] as const // has to be 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"'
聊天中提出了一些解决方案,但在某种程度上都是粗糙的,并且“采取额外的步骤”,真的没有更好的方法吗?
str
let arr = ["A", "B"] as const;
function isAorB(str: string): str is "A" | "B" {
return arr.includes(str as "A" | "B");
}
This works because you’re telling TypeScript, "I know str can only be "A" or "B" for this comparison."
这是错误的!
Set
const arrSet = new Set(["A", "B"] as const);
function isAorB(str: string): str is "A" | "B" {
return arrSet.has(str);
}
这是一个“矫枉过正”,包含可以在不创建新对象的情况下工作!!
let arr = ["A", "B"] as const;
function isAorB(str: string): str is "A" | "B" {
return (arr as readonly string[]).includes(str);
}
If you want to avoid modifying the function, you can cast arr to readonly string[], which loosens the type of includes, This approach sacrifices some type safety but resolves the error.
我同意聊天,这是一个奇怪的选择。
有没有办法在不欺骗编译器或创建新对象的情况下实现这个功能?
输入数组来包含字符串怎么样?
const arr: readonly string[] = ["A","B"];
function isAorB(str: string): str is "A" | "B" {
return arr.includes(str);
}