In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?

前端 未结 3 697
滥情空心
滥情空心 2020-11-22 00:54

When looking at the sourcecode for a tslint rule, I came across the following statement:

if (node.parent!.kind === ts.SyntaxKind.ObjectLiteralExpression) {
          


        
3条回答
  •  暖寄归人
    2020-11-22 01:14

    non-null assertion operator

    With the non-null assertion operator we can tell the compiler explicitly that an expression has value other than null or undefined. This is can be useful when the compiler cannot infer the type with certainty but we more information than the compiler.

    Example

    TS code

    function simpleExample(nullableArg: number | undefined | null) {
       const normal: number = nullableArg; 
        //   Compile err: 
        //   Type 'number | null | undefined' is not assignable to type 'number'.
        //   Type 'undefined' is not assignable to type 'number'.(2322)
    
       const operatorApplied: number = nullableArg!; 
        // compiles fine because we tell compiler that null | undefined are excluded 
    }
    

    Compiled JS code

    Note that the JS does not know the concept of the Non-null assertion operator since this is a TS feature

    "use strict";
    function simpleExample(nullableArg) {
        const normal = nullableArg;
        const operatorApplied = nullableArg;
     }

提交回复
热议问题