代码之家  ›  专栏  ›  技术社区  ›  Steve Lam

是什么!在VueJs中声明道具时

  •  0
  • Steve Lam  · 技术社区  · 6 年前

    现在我偶然发现 ContentChildren decorator 角度的。第一个示例使用了以下语法:

    import {AfterContentInit, ContentChildren, Directive, QueryList} from '@angular/core';
    
    @Directive({selector: 'child-directive'})
    class ChildDirective {
    }
    
    @Directive({selector: 'someDir'})
    class SomeDir implements AfterContentInit {
      @ContentChildren(ChildDirective) contentChildren !: QueryList<ChildDirective>;  // this line is relevant
    
      ngAfterContentInit() {
        // contentChildren is set
      }
    }
    

    感叹号后接冒号 就在 @ContentChildren(ChildDirective) contentChildren this StackOverflow thread 我发现在访问变量或对象属性时,此语法可以用作“非空断言运算符”。

    null

    0 回复  |  直到 7 年前
        1
  •  5
  •   lukasgeiter    7 年前

    我现在的问题是类型定义之前的感叹号是否与普通上下文中的含义完全相同。

    undefined ! 在名称之后,如果不立即初始化,TypeScript将忽略此项,并且不会显示错误:

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

    同样的事情实际上也适用于局部变量:

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

    Playground

    推荐文章