Issue
I'm having issues with switch statements in TypeScript
Tried on multiple code editors, I'm trying to use switch (true) but for some reason the code is failing in the switch statement.
const todoList: string[] | null = [];
function pushItemToTodoList(item: string) {
//COMPILES!!
if (todoList !== undefined && todoList !== null && todoList.length) {
if (todoList.length >= 5) {
console.log("LIST IS FULL!");
}
}
//DOESN'T COPMILE!!
switch (true) {
case todoList !== undefined && todoList !== null && todoList.length:
if (todoList.length >= 5) { //todoList is null???
console.log("LIST IS FULL!");
}
break;
}
}
pushItemToTodoList("clean house");
here is a picture of the error, thank you
Solution
The switch statement by itself does not fail. It simpy does not tolerate case statements with variables. nor conditional operators, only static values. At compiling time, the switch statement builds an index of all the static values in the case statements and their jump positions. You cannot use variables in a case statement because at compile time, these variables are not supposed to be calculated or even exist. Switch - Case statements are super performant, because of indexes with static values and jump positions being pre-compiled. There is a way to solve this specific problem though, combining boolean logic with algebra in the switch statement and static values in the case statements.
Answered By - Shrimpy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.