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

Time:10-15

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!

CodePudding user response:

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

type SpecificArray = ["hello", "goodbye", ...string[]];

CodePudding user response:

You can define your type using a tuple type:

type SpecificArray = ['hello', 'goodbye', ...string[]];

Playground

  • Related