I want to do this in Typescript:
type animals = 'cat' | 'dog'
let selectedAnimals: animals[] = ['cat']
selectedAnimals = [ // <- Type 'string[]' is not assignable to type 'animals[]'
...selectedAnimals,
...(condition ? ['cat'] : [])
]
Link.
The following works, but is there a nicer way than using as animals
?
type animals = 'cat' | 'dog'
let selectedAnimals: animals[] = ['cat']
selectedAnimals = [
...selectedAnimals,
...(['cat' as animals]),
...(['wednesday' as animals]) // <- this also compiles
]
CodePudding user response:
You can add as const
to ['cat']
to give it type readonly ["cat"]
instead of string[]
, and the code will compile without losing type safety. This will also guard against including non-animal arrays:
type animals = 'cat' | 'dog'
let selectedAnimals: animals[] = ['cat']
selectedAnimals = [
...selectedAnimals,
...(['cat'] as const),
// ...(['wednesday'] as const) // <- will fail
]
Alternatively, you could add as const
to the individual elements, e.g. [`cat` as const]
which will type the array as "cat"[]
. (Playground)