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

How to define an array type where it must have specific values?

I’m trying to define a type for an array where the value must contain specific values in a specific order at the beginning of the array.

type SpecificArray = ('hello'|'goodbye'|string)[]

// Currently
const myArray: SpecificArray = [] // okay
const myArray: SpecificArray = [''] // okay
const myArray: SpecificArray = ['something'] // okay
const myArray: SpecificArray = ['hello'] // okay
const myArray: SpecificArray = ['hello', 'goodbye'] // okay
const myArray: SpecificArray = ['hello', 'goodbye', 'something'] // okay

// Desired
const myArray: SpecificArray = [] // fail
const myArray: SpecificArray = [''] // fail
const myArray: SpecificArray = ['something'] // fail
const myArray: SpecificArray = ['hello'] // fail
const myArray: SpecificArray = ['hello', 'goodbye'] // okay
const myArray: SpecificArray = ['hello', 'goodbye', 'something'] // okay

I’ve tried various options, but none have had the desired effect…

type SpecificArray = ('hello'|'goodbye'|string)[]

/* ---- */

type SpecificArray = ['hello'|'goodbye'|string]

/* ---- */

import type { LiteralUnion } from 'type-fest'
type SpecificArray = LiteralUnion<'hello'|'goodbye', string>[]

Thank you in advance!

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

>Solution :

If the order is fixed in your array, then this works:

type SpecificArray = ["hello", "goodbye", ...string[]];
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