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'
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With