码迷,mamicode.com
首页 > 其他好文 > 详细

[TypeScript] Restrict null and undefined via Non-Nullable-Types in TypeScript

时间:2017-11-08 20:11:21      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:appid   explain   ges   es2017   str   compiler   sso   mpi   statement   

This lesson introduces the --strictNullChecks compiler option and explains how non-nullable types differ from nullable types. It also illustrates how you can write safer code by being explicit about null and undefined in the type system.

 

First of all: 

Number, string, boolean types can be assign to null or undefiend.

技术分享

 

If we don‘t want null or undefined, we can turn on "strictNullCheckes" in the tsconfig.json.

{
    "compilerOptions": {
        "strictNullChecks": true
    }
}

技术分享

 

We can fix the compiler error by using unit type:

let text: string | null | undefined;
text = "text";
text = null;
text = undefined;

 

Another thing about vscode autocompletion, as we can see that document.getElementById() return HTMLElement or null:

技术分享

Because of null type, so we cannot get autocompletion in IDE:

技术分享

Typescript force us to do type checking, we can do:

技术分享

As we can see that, once we wrap it into if statement, then we can get autocompletion because typescript now knows that ‘app‘ is only HTMLElmenet type. 

 

Last, in Typescript, we can write sytax like:

const app = document.getElementById("appId")!;

We add ‘!‘ in the end, it tell Typescript, null type is not allowed.

Then we can get autocompletion with if statement. But this is only a valid snytax in typescript.

技术分享

 

[TypeScript] Restrict null and undefined via Non-Nullable-Types in TypeScript

标签:appid   explain   ges   es2017   str   compiler   sso   mpi   statement   

原文地址:http://www.cnblogs.com/Answer1215/p/7805304.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!