Home > Software design >  Utility type for typed array
Utility type for typed array

Time:10-03

There is an array with elements of entities

interface A {
  type: string
}

interface B {
  type: number
}

const a = {} as A
const b = {} as B

const array = [a, b]

The array is of type (A | B)[]
How to describe a utility type so that it returns a typed array [A, B]

CodePudding user response:

What you're looking for is called a const assertion. This can be done by casting the type of array using as const:

const array = [a, b] as const;

See proof-of-concept here on TypeScript playground.

  • Related