true
false
"a"
"Сообщение A"
"Сообщение B"
"b"
"Сообщение C"
null
Прямая реализация этого может выглядеть так;
Код: Выделить всё
function createMessageBasedOnConditions(conditionA: boolean, conditionB: "a" | "b") : string | null {
if(conditionA && conditionB === "a") {
return "Message A";
}
if(!conditionA && conditionB === "a") {
return "Message B"
}
if(conditionA && conditionB === "b") {
return "Message C";
}
// TypeScript has not narrowed the types at this point.
//(parameter) conditionA: boolean
conditionA
//(parameter) conditionB: "a" | "b"
conditionB
return null;
}
Лучшая реализация может выглядеть так:
Код: Выделить всё
function assertUnreachable(values: never): never {
throw new Error("Didn't expect to get here");
}
function createMessageBasedOnConditions(conditionA: boolean, conditionB: "a" | "b") : string | null {
if(conditionA) {
if(conditionB === "a") {
return "Message A";
}
else if (conditionB ==="b"){
return "Message C"
}
return assertUnreachable(conditionB);
}
else {
if (conditionB === "a") {
return "Message B"
}
else if(conditionB==="b") {
// (parameter) conditionA: false
conditionA
//(parameter) conditionB: "b"
conditionB
return null;
}
return assertUnreachable(conditionB);
}
//Unreachable code detected.(7027)
conditionA
conditionB
}
Но это становится довольно громоздким, если мы начинаем говорить о большем количестве перестановок, нам нужно добавить блоки обработки в каждый блок верхнего уровня.
Мне приходит в голову, что на самом деле мне нужен какой-то оператор переключения который может работать с несколькими переменными, например
Код: Выделить всё
function assertUnreachable(values: Array): never {
throw new Error("Didn't expect to get here");
}
function createMessageBasedOnConditions(conditionA: boolean, conditionB: boolean) : string | null {
// Imaginary syntax follows
switch(conditionA, conditionB) {
case true, true: {
return "Message A";
}
case true, false: {
return "Message C";
}
case false, true: {
return "Message B";
}
case false, false {
return null;
}
default: {
assertUnreachable([conditionA, conditionB]);
}
}
}
Но главное преимущество этого, на мой взгляд, заключается в том, что по умолчанию определенно будет обрабатываться все необработанные случаи в одном утверждении AssertUnreachable.>
Подробнее здесь: https://stackoverflow.com/questions/797 ... -variables
Мобильная версия