Re:TypeScript Features to Avoid
by chrismorgan on Thursday January 20, 2022 @08:57AM
(#30008921)
Trouble with your const there as written is that you don’t have a type that’s equal to "GET" | "POST". Fortunately, this can be done without repetition or too much bother:
const HttpMethod = {
Get: 'GET',
Post: 'POST',
} as const;
type HttpMethod = (typeof HttpMethod)[keyof typeof HttpMethod];
Maybe wrap the `{…} as const` in Object.freeze(…) for good measure.It’d be really nice if they’d improve the ergonomics on this in some way (`type Values<T> = T[keyof T]` would reduce it to `type HttpMethod = Values<typeof HttpMethod>`, which is a start but not enough), to make it a genuine and suitable alternative to enum (minus the other frippery that’s generated) and const enum (because it’s pure JavaScript, not an extension).
Besides, there is an straightforward way to remove enums from a program just like removing type annotations: Inline them as static fields of an object.
There is a simple syntactic transformation.
Namespaces can be translated in almost the exactly same way.