简体   繁体   English

初始化变量 Typescript 时,对象可能是“未定义的”

[英]Object is possibly 'undefined' when init a variable Typescript

I have a component in my app like this:我的应用程序中有一个这样的组件:

@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;

But, when i try to compile the app, i get但是,当我尝试编译应用程序时,我得到

Object is possibly 'undefined'

The error is in the variable static = false that is causing that @ViewChild(StripeCardComponent, this.static) card is receiving the variable as possible undefined , but as you can see the variable is not undefined , the variable is a boolean initializated in false ..错误在变量static = false ,导致@ViewChild(StripeCardComponent, this.static) card正在接收变量undefined ,但正如您所看到的变量不是undefined ,变量是一个以false初始化的布尔值..

What can i do to solve this problem?我能做些什么来解决这个问题?

Thank you!谢谢!

You can refer to the Angular's Static Query Migration where it shows that the @ViewChild 2nd parameter is { static: boolean } type, so you should edit yours to:您可以参考 Angular 的静态查询迁移,其中显示@ViewChild 2nd 参数是{ static: boolean }类型,因此您应该将其编辑为:

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

or much better to assign it directly, since this condition will apply upon initialization:或者直接分配它更好,因为此条件将在初始化时适用:

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

@ViewChild, in this case, is a decorator.在这种情况下,@ViewChild 是一个装饰器。 To understand the problem, you need to understand how decorators work and how they apply to methods.要理解这个问题,您需要了解装饰器的工作原理以及它们如何应用于方法。

Original code:原始代码:

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 {}
}

Compiled code:编译代码:

// __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);

After compiling this code, you can see that the decorators modify the prototype class, not its instance.编译这段代码后,你可以看到装饰器修改了原型类,而不是它的实例。 Thus, "this" in the argument "this.static" you pass to the decorator points to no context , and therefore its value is undefined.因此,传递给装饰器的参数“this.static 中的“this”指向 no context ,因此它的值是未定义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM