离开 Angular 组件 @Input 未分配

Leaving Angular Component @Input Unassigned

我有一个组件接受这样的 @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 似乎也不起作用。

您可以添加感叹号以指示 typescript 编译器忽略缺少的默认值。

@Input() thing!: Thing;

虽然使用 @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.');
  }
}

您定义了一个 class 变量,该变量为空(未定义)但您将其声明为 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;