简体   繁体   中英

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 ..

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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