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"
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'. Types of property 'races' are incompatible. Type 'string[]' is not assignable to type '("HUMAN" | "ORC" | "ELF" | "DWARF")[]'. Type 'string' is not assignable to type '"HUMAN" | "ORC" | "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]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With