3 ms·
I use it in Typescript often. Very useful. type Verb = 'GET' | 'POST' | 'PUT' | 'DELETE'; export type TerminusType = 'ICAO' | 'IATA' | 'LOCODE' | 'ADDRESS' |
by crucialfelix 5y ago
I use it in Typescript often. Very useful.
type Verb = 'GET' | 'POST' | 'PUT' | 'DELETE';
export type TerminusType = 'ICAO' | 'IATA' | 'LOCODE' | 'ADDRESS' | 'LATLNG';
It's much better than just assuming it's a string and hoping you don't make a typo.
If the value is supplied from user input then it ensures that you write checks or switch cases.
- growse 5y ago> I use it in Typescript often. Very useful. > type Verb = 'GET' | 'POST' | 'PUT' | 'DELETE'; > export type TerminusType = 'ICAO' | 'IATA' | 'LOCODE' | 'ADDRESS' | 'LATLNG'; > It's much better than just assuming it's a string and hoping you don't make a typo. > If the value is supplied from user input then it ensures that you write checks or switch cases. Conceptually, how is this different to an enum?
- acjohnson55 5y agoIt can be used as an enum and might be more convenient in places where you don't need to bother converting between string data outside the system and enum data types. It also plays nicely with union types, so that you can very quickly define as hoc enums directly in your function declarations, which might be useful if there's only one or two usages of a particular enum, or a section of code where the allowable values very quickly changes. You basically get a lot of expressiveness without boilerplate, which can be pretty convenient.
- crucialfelix 5y agoAn Enum in ts is weird. It's not just a type, it's something compiles to something in the runtime. So to use the value you have to import the Enum and use that. const handlers = { '/': { Verbs.GET: () => .... Verbs.POST: () => ... Whereas: const handlers = { '/': { GET: () => .... PAWST: //nope! must be one of GET | POST | PUT | DELETE Basically it's a lot less work and you don't need to import the enum and maintain it.
- stickfigure 5y agoConceptually, it's very much like an enum. Except that you can't enumerate them at runtime because there is no runtime representation. This can be very frustrating. There's a hack, it looks like: export const VERBS = ['GET', 'POST', 'PUT', 'DELETE'] as const; type VerbTuple = typeof VERBS; export type Verb = VerbTuple[number]; A real enum would be better, but would violate the "typescript is just javascript" rule.