Usage of the never type

The never is a variable that should never be set. This might sound useless at first but can be useful in a case where you want to ensure that nothing falls into a particular code path. A function rarely returns never, but it can happen. This is the case if you are having a function that does not allow you to finish the method to execute or return any variable; hence, it never fully returns. This can be coded using an exception:

function returnNever(i: number): never {

// Logic here

if (i === 0) {
throw Error("i is zero");
} else {
throw Error("i is not zero");
}

// Will never reach the end of the function

}

Never occurs when you are writing code and you are writing a condition that cannot occur and that TypeScript infers the type by the usage of your code. This can happen if you have several conditions and that one englobe another making some variable fall into the never scenario. It can also happen if you have all the variable values covered by condition and have an else statement (or default with a switch case). The value cannot have any other value than never been assigned, since all values are checked. Here is an illustration of the possibility:

type myUnion = "a" | "b";

function elseNever(value: myUnion) {
if (value === "a") {
value; // type is “a”
} else if (value === "b") {
value; // type is “b”
} else {
value; // type is never
}
}

In practice, the never type is used for checking whether all values of an enum or a union have conditions that took care of all the values. This allows creating a validation when a developer adds a value to the enum or the union but forgets to add a condition. The lack of the condition makes the code fall through the exhaustive check. TypeScript is smart enough to verify all cases and understand that the code might go in the function that takes a never parameter, which is not allowed because nothing can be assigned to never:

type myUnion = "a" | "b";
let c: myUnion = Math.random() > 0.5 ? "a" : "b";

if (c == "a") {
console.log("Union a");
} else {
exhaustiveCheck(c); //”b” will fallthrough
}

function exhaustiveCheck(x: never): never {
throw new Error("");
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.171.153