简体   繁体   English

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

[英]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.

相关问题 Typescript 类型的数组只能包含特定列表中的元素 - Typescript type for an array that can contain only elements from a specific list 我可以在打字稿中定义字符串数组和未定义的数组吗? - Can I define array of strings and undefined in typescript? 定义对象以仅包含特定类型的元素 - Define objects to only contain elements of specific type 如何在 TypeScript 中定义一个简单的字符串数组 - How to define a simple array of strings in TypeScript 在 Typescript 中,我如何将 map 接口的键转换为特定字符串的数组? - In Typescript, how can I map the keys of an interface into an array of specific strings? TypeScript:从字符串数组定义联合类型 - TypeScript: Define a union type from an array of strings 如何在 TypeScript 接口中定义字符串数组? - How to define an array of strings in TypeScript interface? Typescript 如何定义一个类型来检查一个字符串是否包含特定的 substring - Typescript how to define a type to check the if a string contain specific substring 在打字稿中定义对象类型以包含特定的属性键 - Define in typescript object type to contain a specific property key 如何过滤打字稿中的对象数组,以便仅保留包含可选键的对象(并且知道打字稿)? - How can I filter an array of objects in typescript such that only objects that contain an optional key are left (and typescript is aware)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM