3 ms·
That's really interesting. doTheThing(readFromUser()) What does the compiler do in cases where you have strings coming in like this?
by Sirenos 4y ago
That's really interesting.
doTheThing(readFromUser())
What does the compiler do in cases where you have strings coming in like this?
- paavohtl 4y agoIt gives a type error, because strings are not assignable to string literals. https://www.typescriptlang.org/play?#code/FAEwpgxgNghgTmABAMwK4DsIBcCWB7dREPAFQAsxyd0BzACgjyjzgC5EAiAJQFEARDogA+nAOK8eAOQ4BKdgDc8OEKEiwEKDNnyEEMEADE4eALYBVAM5g4dOYgtY41GsFCkKVWnT2Hj5qzYyMsBAA https://www.typescriptlang.org/play?#code/FAEwpgxgNghgTmABAM... However, if you check or assert that the returned value is one of the accepted literals, compiler accepts it: https://www.typescriptlang.org/play?#code/FAEwpgxgNghgTmABAMwK4DsIBcCWB7dREPAFQAsxyd0BzACgjyjzgC5EAiAJQFEARDogA+nAOK8eAOQ4BKdgDc8OEKEiwEKDNnyEEMEADE4eALYBVAM5g4dOYgtY41GsGCN0DxNQAOqLIgBeRD1DY3MrGxlXHGREOh8-QICggHJePhThEQT-ZNTxHikUmUQAb2BEIlIKKlp49F8sKIBfYCA https://www.typescriptlang.org/play?#code/FAEwpgxgNghgTmABAM... This is one of the classic examples of flow-sensitive typing in TS.
- phpnode 4y agoit'll tell you that `string` cannot be assigned to type `"RED" | "GREEN"`, and so you'll need to write a function that refines the type correctly, e.g. function isValidInput(input: unknown): input is "RED" | "GREEN" { return input === "RED" || input === "GREEN"; } const input = readFromUser(); if (isValidInput(input)) { doTheThing(input); // no type error }
- moron4hire 4y agoIt's an error, as the plain `string` type doesn't satisfy the union. You'll need to perform type assertions to make the return type down before passing it as a parameter.