Skip to content

Instantly share code, notes, and snippets.

@brandonpapworth
Last active January 31, 2022 09:03
Show Gist options
  • Save brandonpapworth/ab04ccc82238117ed486d003824dae9d to your computer and use it in GitHub Desktop.
Save brandonpapworth/ab04ccc82238117ed486d003824dae9d to your computer and use it in GitHub Desktop.
[WIP] TypeScript: Creating "Enums" from Tuple of String Literals

Creating Enums from Tuple of String Literals

Description

It is as it sounds: this function will create something similar to an enum (in this case, an object with a null prototype) from a tuple of string literals.

Why?

Even though native enums have some convenient benefits, they can get a little "wordy" when you wish them to work like holders of string constants.

export enum MyConfigConstants {
  name = 'name',
  DERP = 'DERP',
  location = 'location',
  WILL = 'WILL',
  THIS = 'THIS',
  NEVER = 'NEVER',
  END = 'END',
}

So I figure why not do this in a simpler way?

import { enumFromTuple } from './enum-from-tuple'

export const MyConfigConstants = enumFromTuple([
  'name',
  'DERP',
  'location',
  'WILL',
  'THIS',
  'NEVER',
  'END',
] as const) // <- `as const` is important!

This isn't purported to be a "good" solution. This is more a demonstration of the TupleToObject type which is able to take a tuple of string literals and create keys with equivalent values from each of the tuple elements.

export type TupleToObject<T extends readonly string[]> = {
readonly [K in Exclude<keyof T, keyof string[]> as T[K] extends string ? T[K] : never]: T[K]
}
export function enumFromTuple<T extends string, U extends readonly [T, ...T[]]>(tuple: U): TupleToObject<U> {
const enumObject = Object.create(null)
for (const element of tuple) {
enumObject[element] = element
}
return enumObject
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment