【问题标题】:Leaving Angular Component @Input Unassigned保留 Angular 组件 @Input 未分配
【发布时间】:2021-05-16 00:31:54
【问题描述】:

我有一个像这样接受@Input 的组件:

@Input() thing:Thing; // error!

这以通常的方式传递给组件:

<my-component [thing]="thatThing"></my-component>

我认为由于严格模式,我得到以下编译器错误:Property 'thing' has no initializer and is not definitely assigned in the constructor. 有没有办法在不填充虚拟数据并保持严格模式的情况下摆脱它(如果这确实是原因),并且只是依赖于从实例化组件的人那里填充的输入?我真的没有分配给thing 的默认值,而nullundefined 似乎也不起作用。

【问题讨论】:

    标签: angular typescript data-binding


    【解决方案1】:

    您可以添加一个感叹号以指示打字稿编译器忽略缺少的默认值。

    @Input() thing!: Thing;

    【讨论】:

    • 你可以这样做,但它实际上绕过了严格模式,如果 this.thing 未定义,这肯定会导致错误。你的回答比接受的答案有更多的赞成票,但它建议一种不好的做法。他真正想做的是将变量定义为Thing | undefined:@Input() thing: Thing | undefined;
    【解决方案2】:

    虽然使用@Input() thing!: Thing; 确实消除了编译器警告,但最好不要忽略@Inputs 始终可以是undefined这一事实

    如果你想保持严格,你可以使用@Input() thing: Thing | undefined;

    如果您确实想使用@Input() thing!: Thing;,我建议您这样防范:

    public ngAfterViewInit(): void {
      // thing should be defined here, if it was assigned a value
      if(!this.thing){
        throw new Error('thing is not defined, please provide a value.');
      }
    }
    

    【讨论】:

      【解决方案3】:

      您定义了一个为空(未定义)的类变量,但您将其声明为Thing 类型。这实际上是错误的,因为此时未定义而不是Thing

      正确的输入是“Thing OR undefined”:

      @Input() thing: Thing | undefined;
      // or shorter
      @Input() thing?: Thing;
      

      如果您想使用 this.thing 并且不首先检查它是否确实存在,这样做会使编译器报错:

      this.thing.toString(); // Error
      
      if (typeof this.thing !== 'undefined') {
         this.thing.toString(); // Ok
      }
      

      这可能有点烦人,但实际上是正确的,因为如果使用组件而不定义它们,所有输入都可能是未定义的:

      <my-component></my-component>
      

      如果您想解决这个问题(我不建议这样做),因为您知道“我是一个完美的人,并且在不定义输入的情况下永远不会犯错误”,您可以告诉编译器您的变量将被定义:

      @Input() thing!: Thing;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-08-03
        • 1970-01-01
        • 2019-04-12
        • 2013-04-03
        • 2011-06-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多