Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create union type annotation from dynamically generated array in Typescript

Giving a generated array from a reduce, how is it possible to create a union type from this array?

import someFancyObject from 'some/modules';
const generatedArray = someFancyObject.reduce((acc, val, i) => {...}, []);

// generatedArray would be like: ['a', 'b', 'c']

type UnionFromArray = ???

// UnionFromArray would be like 'a' | 'b' | 'c'
like image 642
DavideCariani Avatar asked Jul 10 '26 08:07

DavideCariani


1 Answers

You can either infer an array from function argument or declare constant (immutable) array:

const arr = ['a', 'b', 'c'] as const
type UnionFromArray = (typeof arr)[number] // "a" | "b" | "c"

// OR

const unionFromArray = <
  T extends string,
  Arr extends T[]
>(arr: [...Arr]): Arr[number] => null as any

const result = unionFromArray(['a', 'b', 'c']) // // "a" | "b" | "c"
like image 73
captain-yossarian Avatar answered Jul 13 '26 22:07

captain-yossarian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!