Skip to content

Instantly share code, notes, and snippets.

@fuji44
Created June 22, 2023 14:47
Show Gist options
  • Save fuji44/967adad71c03ed7f801eb5995f729cca to your computer and use it in GitHub Desktop.
Save fuji44/967adad71c03ed7f801eb5995f729cca to your computer and use it in GitHub Desktop.
Interoperation between constant arrays and type definitions in TypeScript

Interoperation between constant arrays and type definitions in TypeScript

export const keyArray = ["key1", "key2", "key3"] as const;

export type Key = typeof keyArray[number];

export function isKey(value: string): value is Key {
  return (keyArray as readonly string[]).includes(value);
}

export function isKeys(values: string[]): values is Key[] {
  return values.every((key) => isKey(key));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment