Hands-On Full Stack Web Development with Angular 6 and Laravel 5
上QQ阅读APP看书,第一时间看更新

Using the never type

The never type was introduced in TypeScript 2.0; it implies a value that never occurs. At first glance, it may seem strange, but it can be used in some situations.

Let's look at what the official documentation says about it:

The  never type represents the types of values that never occur. Specifically, never is the return type for functions that never return, and never is the type for variables under type guards that are never true.

Suppose that a messaging function that is called within another function specifies the callback.

It would look something like the following code:

const myMessage = (text: string): never => {
throw new Error(text);
}
const myError = () => Error('Some text here');

Another example would be checking a value that is a string and number at the same time, such as the following:

function neverHappen(someVariable: any) {
if (typeof someVariable === "string" && typeof someVariable ===
"number") {
console.log(someVariable);
}
}
neverHappen('text');