zoukankan      html  css  js  c++  java
  • [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.

  • 相关阅读:
    文件操作
    验证进程 及jion方法
    进程笔记
    网络通信名词总结
    网络QQ聊天代码实例
    网络通信 粘包和 缓冲器
    udp
    UVALive 3983 Robotruck (单调队列,dp)
    UVA 10891 Game of Sum (决策优化)
    Uva 10635 Prince and Princess (LCS变形LIS)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/7805304.html
Copyright © 2011-2022 走看看