Typescript定义只能包含特定字符串的数组

idfiyjo8  于 2023-04-22  发布在  TypeScript
关注(0)|答案(2)|浏览(211)

我很困惑,为什么下面的错误,我有字符界面

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"]
}

错误内容如下
[ts]类型'{ races:string[] }'不可分配给类型' Tavern '。属性'races'的类型不兼容。类型'string[]'不可分配给类型'(“HUMAN”|“ORC”|“ELF”|“DWARF”)[]“。类型”string“不可分配给类型”“HUMAN”|“ORC”|“ELF”|“侏儒”

1cklez4t

1cklez4t1#

这是一个旧的 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]
}
tktrz96b

tktrz96b2#

我想这可能是你写问题时的一个typescript bug。Typescript v5.0.4(在这个答案的时候是最新的)编译你的代码没有问题:

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

interface Tavern {
  races: Character['race'][]
}

const tavern: Tavern = {
   races: ["ORC", "ELF", "HUMAN", "DWARF"]
}

相关问题