Hacker News new | ask | show | jobs
by gnud 1401 days ago
You can approximate something by defining the valid TokenTable keys as an enum, and using a mapped type for the actual TokenTable type.

There's some boilerplate in the definition, but it's fairly clean and non-repetitive. And easy to use in the "client code".

https://www.typescriptlang.org/play?#code/KYOwrgtgBAKg9ga1AS...

2 comments

You can also write the array first, without using enum:

const tokens = ['parenOpen', 'bang', 'plus', 'minus'] as const;

type Token = typeof tokens[number];

type TokenTable<T> = Record<Token, T> // alias for { [key in Token]: T }

const isToken = (t: string): t is Token => tokens.includes(t);

const patterns: TokenTable<RegExp> = { bang: /\+/, // rest }

You put some real effort into the example. It's the opposite approach of how I did it, yet works just as well. Thanks!