我很困惑为什么会出现以下错误,我有字符界面

interface Character {
 race: "ORC" | "ELF" | "HUMAN" | "DWARF"
}

还有另一个界面酒馆
interface Tavern {
  races: Character['race'][]
}

这里的想法是 Races 是一个只能是 "ORC" | "ELF" | "HUMAN" | "DWARF" 的字符串数组

出于某种原因,当我像这样使用它时出现错误
const tavern: Tavern = {
   races: ["ORC", "ELF", "HUMAN", "DWARF"]
}

错误如下

最佳答案

这是一个旧的 typescript 故事,您很可能必须这样做:

const tavern: Tavern = {
   races: ["ORC", "ELF", "HUMAN", "DWARF"] as Array<Character['race']>
}

可能
type Race = "ORC" | "ELF"

const tavern: Tavern = {
   races: ["ORC" as Race, "ELF" as Race]
}

这应该有效
enum Race = { ORC, ELF }

interface Tavern {
  races: Race[]
}

const tavern: Tavern = {
   races: [Race.ORC, Race.ELF]
}

10-07 21:51