簡體   English   中英

初始化變量 Typescript 時,對象可能是“未定義的”

[英]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 的靜態查詢遷移,其中顯示@ViewChild 2nd 參數是{ 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);

編譯這段代碼后,你可以看到裝飾器修改了原型類,而不是它的實例。 因此,傳遞給裝飾器的參數“this.static 中的“this”指向 no context ,因此它的值是未定義的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM