初始化变量时对象可能是 'undefined'

Object is possibly 'undefined' when init a variable Typescript

我的应用程序中有这样一个组件:

@Component({
  selector: 'app-payment-intent',
  templateUrl: './payment-intent.component.html',
  styleUrls: ['./payment-intent.component.css']
})
export class PaymentIntentComponent implements OnInit {

  static = false;
  @ViewChild(StripeCardComponent, this.static) card: StripeCardComponent;

但是,当我尝试编译应用程序时,我得到

Object is possibly 'undefined'

变量 static = false 中的错误导致 @ViewChild(StripeCardComponent, this.static) card 正在尽可能接收变量 undefined,但如您所见,变量不是 undefined, 该变量是在 false..

中初始化的布尔值

我该怎么做才能解决这个问题?

谢谢!

您可以参考 Angular 的 Static Query Migration 其中显示 @ViewChild 第二个参数是 { static: boolean } 类型,因此您应该将其编辑为:

@ViewChild(StripeCardComponent, { static: this.static }) card: StripeCardComponent;

或者直接赋值更好,因为这个条件将在初始化时应用:

@ViewChild(StripeCardComponent, { static: false }) card: StripeCardComponent;

@ViewChild,在本例中,是一个装饰器。要理解这个问题,您需要了解装饰器的工作原理以及它们如何应用于方法。

原代码:

function decorator(value?:any) {
  return function <T>(target: unknown, propertyKey: string, descriptor: TypedPropertyDescriptor<T>): void {
    console.log('value:', value);
  };
}

class Bar {
    @decorator(this)
    public foo():void {}
}

编译代码:

// __decorate and __metadata declarations skipped

function decorator(value) {
  return function (target, propertyKey, descriptor) {
    console.log('value:', value);
  };
}

class Bar {
  foo() { }
}

__decorate([
  decorator(this),
  __metadata("design:type", Function),
  __metadata("design:paramtypes", []),
  __metadata("design:returntype", void 0)
], Bar.prototype, "foo", null);

编译这段代码后,你可以看到装饰器修改了原型class,而不是它的实例。因此,传递给装饰器的参数“this.static”中的 “this” 没有指向上下文 ,因此它的值为未定义。