0

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']
manidos
  • 3,244
  • 4
  • 29
  • 65
  • Does this answer your question? [How to transform union type to tuple type](https://stackoverflow.com/questions/55127004/how-to-transform-union-type-to-tuple-type) – kaya3 May 09 '21 at 02:02

1 Answers1

2

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

Nishant
  • 54,584
  • 13
  • 112
  • 127