|
|
|
|
|
by theK
1426 days ago
|
|
Am I the only one that feels uncomfortable with all that usage of strings in TS’s type system? Why not use pure literals instead of string literals? This is a genuine question, I’m trying to find out what the pros and cons where in the decision making process. |
|
I.e. if I write
I'm guaranteeing that the value of 'bar' on any object of that type must be "Vodka" - the type of bar is not string, it's literally "Vodka" because string values can be types.This seems a little obscure and pointless, but you can put these string types in a union, and enforce that a value must be one of many values.
You can also define a type like and then at compile time know that if mountain.name === "EVEREST" then height === 8848 because the types of name and height aren't string and number, they're "EVEREST" | "K2" and 8848 | 8611, and the compiler is smart enough to work out one based on the other.==============================================
For extra context - a lot of this is for interoptability with Javascript code - you want to call some Javascript function with a stringly typed enum, and enforce only passing in valid values, but the Javascript code still just deals with strings.
A lot of Typescripts kind of insane flexibility is so you can introduce type safety to all sorts of dynamic Javascript code, without having to make sacrifices on the dynamic-ness of it.
Turns out this flexibility is actually kinda awesome to have in general even when you're not trying to refactor an existing JS codebase.