! operator in typescript after object method

前端 未结 1 1693
醉话见心
醉话见心 2020-11-27 04:37

I have an object X with a method getY() returning an object Y with a method a(), in typescript. What does it mean an expr

相关标签:
1条回答
  • 2020-11-27 05:18

    It's called the "Non-null assertion operator" and it tells the compiler that x.getY() is not null.

    It's a new typescript 2.0 feature and you can read about it in the what's new page, here's what it says:

    A new ! post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. Specifically, the operation x! produces a value of the type of x with null and undefined excluded. Similar to type assertions of the forms x and x as T, the ! non-null assertion operator is simply removed in the emitted JavaScript code.

    // Compiled with --strictNullChecks
    function validateEntity(e?: Entity) {
        // Throw exception if e is null or invalid entity
    }
    
    function processEntity(e?: Entity) {
        validateEntity(e);
        let s = e!.name;  // Assert that e is non-null and access name
    }
    

    Edit

    There's an issue for documenting this feature: Document non-null assertion operator (!)

    0 讨论(0)
提交回复
热议问题