manidos
manidos

Reputation: 3464

How to describe an array with string literal union?

I have this simple union type.

type ItemType = 'type1' | 'type2' | 'type3'

My goal is to define an array using this type so that it contains all string literals from ItemType in no specific order.

For example, ['type1', 'type2', 'type3'] and ['type3', 'type2', 'type1'] are VALID.

But, ['type1', 'type2'] and ['type1', 'type2', 'type3', 'type4'] are INVALID

I only got so far:

const myArray: ItemType[] = ['type1', 'type2', 'type3']

Upvotes: 0

Views: 30

Answers (1)

Nishant
Nishant

Reputation: 55856

What you want is an ordered set of fixed types... also known as Tuple

type ItemType = 'type1' | 'type2' | 'type3'

type ItemTuple = [ItemType, ItemType, ItemType, ];

// Valid
const t1: ItemTuple = ['type1', 'type2', 'type3'];
const t2: ItemTuple = ['type3', 'type2', 'type1'];

// Invalid
const t3: ItemTuple = ['type1', 'type2']; 
// Type '["type1", "type2"]' is not assignable to type 'ItemTuple'.

const t4: ItemTuple = ['type1', 'type2', 'type3', 'type4'] 
// Type '["type1", "type2", "type3", "type4"]' is not assignable to type 'ItemTuple'.

Typescript playground link: https://tsplay.dev/Nl0j5N

Upvotes: 2

Related Questions