Skip to content

Instantly share code, notes, and snippets.

@Shrugsy
Last active March 31, 2021 14:12
Show Gist options
  • Save Shrugsy/4732111752f1d96da019a0f54a0a2772 to your computer and use it in GitHub Desktop.
Save Shrugsy/4732111752f1d96da019a0f54a0a2772 to your computer and use it in GitHub Desktop.
Get a union type derived from values of a const asserted array
/**
* Get a union type derived from values of a const asserted array.
* @example
* const values = ['foo', 'bar'] as const;
* type Val = ArrayValues<typeof values>;
* // => 'foo' | 'bar'
*
* See https://github.com/microsoft/TypeScript/issues/28046#issuecomment-607145719
*/
export type ArrayValues<T extends ReadonlyArray<unknown>> = T[number];
@Shrugsy
Copy link
Author

Shrugsy commented Mar 31, 2021

Previous version:

// See https://github.com/microsoft/TypeScript/issues/28046#issuecomment-480516434
export type ArrayValues<T extends ReadonlyArray<unknown>> = T extends ReadonlyArray<infer ElType>
  ? ElType
  : never;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment