4 ms·
It gives a type error, because strings are not assignable to string literals. https://www.typescriptlang.org/play?#code/FAEwpgxgNghgTmABAMwK4DsIBcCWB7dREPAFQAs
by paavohtl 4y ago
It 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.