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

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[TypeScript] Restrict null and undefined via Non-Nullable-Types in TypeScript相关的知识,希望对你有一定的参考价值。

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.

 


 

Update:

Another approach:

const app = document.getElementById("appId") as NonNullable<HTMLElement>;

 

以上是关于[TypeScript] Restrict null and undefined via Non-Nullable-Types in TypeScript的主要内容,如果未能解决你的问题,请参考以下文章

LayaBox---TypeScript---类型推论

Typescript Angular:如果未定义(未使用),默认将所有类成员设置为 Null

反反注入 修改__RESTRICT,__restrict工具

为啥clang忽略__restrict__?

C++中的restrict关键字是啥意思?

RESTRICT 和 NO ACTION 的区别