Exclamation Mark in type definition

后端 未结 1 2034
旧巷少年郎
旧巷少年郎 2021-01-19 04:47

Currently I stumbled upon the ContentChildren decorator of Angular. In the first code example the following syntax is used:

         


        
1条回答
  •  鱼传尺愫
    2021-01-19 04:52

    My question is now whether the exclamation mark before a type definition has exactly the same meaning like in a normal context.

    No that's actually not the same thing, in this context it does something different. Normally when you declare a member (which doesnt' include undefined in it's type) it has to be initialized directly or in the constructor. If you add ! after the name, TypeScript will ignore this and not show an error if you don't immediately initialize it:

    class Foo {
      foo: string; // error: Property 'foo' has no initializer and is not definitely assigned in the constructor.
      bar!: string; // no error
    }
    

    The same thing actually applies to local variables as well:

    let foo: string;
    let bar!: string;
    
    console.log(foo); // error: Variable 'foo' is used before being assigned.
    console.log(bar); // no error
    

    Playground

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