While doing a Lynda tutorial on Typescript ( https://www.lynda.com/Visual-Studio-tutorials/TypeScript-types-part-2/543000/565613-4.html#tab ), I hit a snag. The sample code
That's because the compiler already knows that the case temperature.hot
will never happen: the variable temp
is given the enum literal type temperature.cold
, which can only be assigned that value itself (or null if there are no strict null checks). As temperature.hot
is not a compatible value here, the compiler throws an error.
If we discard the information about the literal (by casting or retrieving the value from a function):
function how_cold(celsius: number): temperature {
return celsius > 40 ? temperature.hot : temperature.cold;
}
The code will then compile:
let temp = how_cold(35); // type is "temperature"
switch (temp) {
case temperature.cold:
console.log("Brrr....");
break;
case temperature.hot:
console.log("Yikes...")
break;
}
Alternatively, prepending +
to the value works because it converts the value to a number, which will also widen the type's scope and make it compatible with all enum variants, as well as other numbers.
let temp = temperature.cold;
switch (+temp) {
case temperature.cold:
console.log("Brrr....");
break;
case temperature.hot:
console.log("Yikes...")
break;
case 5:
console.log("What??");
break;
}