#How can I invert the types of a const array?

5 messages · Page 1 of 1 (latest)

mighty island
#

I am trying to take an as const array of strings, pass it through a function and have the function return an inverted object where
the array values become keys, and the indexes become values, while preserving full types.

Example:

const FRUIT = invert([
  'APPLE',
  'BANANA',
  'MANGO',
] as const);

I'd like typeof FRUIT to be identical to typeof FRUIT2 from this example:

const FRUIT2 = {
  APPLE: 0,
  BANANA: 1,
  MANGO: 2,
} as const;

Is this possible?

cloud portalBOT
#
jakoxb#0

Preview:ts type InvertTuple<T extends readonly string[]> = { [K in keyof T & `${number}` as T[K]]: K extends `${infer N extends number}` ? N : never } function invert<const T extends readonly string[]>(arr: T): InvertTuple<T> { return Object.fromEntries(arr.map((value, i) => [value, i])) as InvertTuple<T>; ...

unique heart
#

keyof T & `${number}` to only consider numeric keys (not all these Array.prototype methods)

#

and K looks like "0" so the number has to be inferred

mighty island
#

Wow, thanks that is absolutely mind blowing!