- Learn React with TypeScript 3
- Carl Rippon
- 256字
- 2021-06-10 19:16:32
Never
The never type represents something that would never occur and is typically used to specify unreachable areas of code. Again, this doesn't exist in JavaScript.
Time for an example:
- Type the following code into the TypeScript playground:
function foreverTask(taskName: string): never {
while (true) {
console.log(`Doing ${taskName} over and over again ...`);
}
}
The function invokes an infinite loop and never returns, and so we have given it a type annotation of never. This is different to void because void means it will return, but with no value.
In the preceding example, we used a JavaScript template literal to construct the string to log to the console. Template literals are enclosed by back-ticks ( ``) and can include a JavaScript expression in curly braces prefixed with a dollar sign ( ${expression}). Template literals are great when we need to merge static text with variables.
- Let's change the foreverTask function to break out of the loop:
function foreverTask(taskName: string): never {
while (true) {
console.log(`Doing ${taskName} over and over again ...`);
break;
}
}
The TypeScript compiler quite rightly complains:
- Let's now remove the break statement and the never type annotation. If we hover over the foreverTask function name with our mouse, we see that TypeScript has inferred the type to be void, which is not what we want in this example:
The never type is useful in places where the code never returns. However, we will probably need to explicitly define the never type annotation because the TypeScript compiler isn't smart enough yet to infer that.
推薦閱讀
- 數(shù)據(jù)庫(kù)系統(tǒng)原理及MySQL應(yīng)用教程(第2版)
- C# 7 and .NET Core Cookbook
- 大學(xué)計(jì)算機(jī)基礎(chǔ)實(shí)驗(yàn)教程
- Java EE框架整合開(kāi)發(fā)入門(mén)到實(shí)戰(zhàn):Spring+Spring MVC+MyBatis(微課版)
- Rust編程從入門(mén)到實(shí)戰(zhàn)
- Reactive Programming with Swift
- Visual C
- Learning Zurb Foundation
- 從零開(kāi)始學(xué)C語(yǔ)言
- App Inventor 2 Essentials
- OpenCV Android Programming By Example
- Python 快速入門(mén)(第3版)
- Android智能手機(jī)APP界面設(shè)計(jì)實(shí)戰(zhàn)教程
- HTML5/CSS3/JavaScript技術(shù)大全
- Linux Networking Cookbook