我很困惑为什么以下错误,我有字符界面
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'。 属性“种族”的类型不兼容。 类型'string []'不能分配给类型'(“ HUMAN” |“ ORC” |“ ELF” |“ DWARF”)[]'。 类型'string'不能分配给类型'“ HUMAN” | “ ORC” | “ ELF” | “ DWARF””。
答案 0 :(得分:3)
这是一个古老的打字稿故事,您很可能必须这样做:
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]
}