打字稿,数组包含错误:“字符串”类型的参数不能分配给“A”类型的参数 | “B”'

问题描述 投票:0回答:1

我所遇到的问题可以归结为以下错误的打字稿代码,

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"'

聊天中提出了一些解决方案,但在某种程度上都是粗糙的,并且“采取额外的步骤”,真的没有更好的方法吗?

  1. 选项 1:缩小
    str
  2. 的类型
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."
这是错误的!

  1. 选项 2:使用
    Set
const arrSet = new Set(["A", "B"] as const);

function isAorB(str: string): str is "A" | "B" {
  return arrSet.has(str);
}

这是一个“矫枉过正”,包含可以在不创建新对象的情况下工作!!

  1. 选项 3:将 arr 转换为更宽松的类型
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.
我同意聊天,这是一个奇怪的选择。

有没有办法在不欺骗编译器或创建新对象的情况下实现这个功能?

arrays typescript string types
1个回答
0
投票

输入数组来包含字符串怎么样?

const arr: readonly string[] = ["A","B"];
function isAorB(str: string): str is "A" | "B" {
    return arr.includes(str);
}
© www.soinside.com 2019 - 2024. All rights reserved.