Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Spread into array of literal types

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

type animals = 'cat' | 'dog'

let selectedAnimals: animals[] = ['cat']

selectedAnimals = [
    ...selectedAnimals,
    ...(['cat' as animals]),
    ...(['wednesday' as animals]) // <- this also compiles
]

>Solution :

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
]

TypeScript playground

Alternatively, you could add as const to the individual elements, e.g. [`cat` as const] which will type the array as "cat"[]. (Playground)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading