[英]Typescript define array that can contain only specific strings
I'm confused to why following errors, I have character interface 我很困惑为什么出现以下错误,但我有字符界面
interface Character {
race: "ORC" | "ELF" | "HUMAN" | "DWARF"
}
And another interface tavern 和另一个接口酒馆
interface Tavern {
races: Character['race'][]
}
Idea here is that races is an array of strings that can only be "ORC" | "ELF" | "HUMAN" | "DWARF"
这里的想法是races是只能是
"ORC" | "ELF" | "HUMAN" | "DWARF"
的字符串数组。 "ORC" | "ELF" | "HUMAN" | "DWARF"
For some reason I get an error when I use it like this 由于某种原因,当我像这样使用它时会出现错误
const tavern: Tavern = {
races: ["ORC", "ELF", "HUMAN", "DWARF"]
}
Error reads as follows 错误内容如下
[ts] Type '{ races: string[] }' is not assignable to type 'Tavern'.
[ts]类型'{races:string []}'不可分配给类型'Tavern'。 Types of property 'races' are incompatible.
属性“种族”的类型不兼容。 Type 'string[]' is not assignable to type '("HUMAN" | "ORC" | "ELF" | "DWARF")[]'.
类型'string []'不能分配给类型'(“ HUMAN” |“ ORC” |“ ELF” |“ DWARF”)[]'。 Type 'string' is not assignable to type '"HUMAN" |
类型'string'不能分配给类型'“ HUMAN” | "ORC" |
“ ORC” | "ELF" |
“ ELF” | "DWARF"'.
“侏儒”'。
this is an old typescript story, you will most likely have to do this: 这是一个古老的打字机故事,您很可能必须这样做:
const tavern: Tavern = {
races: ["ORC", "ELF", "HUMAN", "DWARF"] as Array<Character['race']>
}
possibly 或者
type Race = "ORC" | "ELF"
const tavern: Tavern = {
races: ["ORC" as Race, "ELF" as Race]
}
this should work 这应该工作
enum Race = { ORC, ELF }
interface Tavern {
races: Race[]
}
const tavern: Tavern = {
races: [Race.ORC, Race.ELF]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.