官术网_书友最值得收藏!

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:

  1. 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.
  1. 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:

  1. 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.

主站蜘蛛池模板: 乌拉特中旗| 天全县| 惠水县| 南部县| 华坪县| 汉川市| 正安县| 龙陵县| 曲阜市| 德化县| 顺义区| 韶关市| 玛纳斯县| 乌审旗| 贵州省| 大洼县| 光泽县| 安国市| 巫溪县| 曲阳县| 启东市| 文登市| 达尔| 扬州市| 永平县| 积石山| 永春县| 桂林市| 建平县| 井陉县| 巨鹿县| 江口县| 天长市| 曲阳县| 张掖市| 绥德县| 舒兰市| 砀山县| 新和县| 宜昌市| 惠来县|