Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript define array that can contain only specific strings

Tags:

typescript

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"'.

like image 878
Ilja Avatar asked Jan 28 '23 17:01

Ilja


1 Answers

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]
}
like image 82
Daniel Khoroshko Avatar answered Jan 31 '23 22:01

Daniel Khoroshko