簡體   English   中英

在Type 2中使用Angular 2中的類型

[英]Using Types in Angular 2 with TypeScript

我的AppComponent中有以下方法:

connectToTweetStream() {
  this._tweetService.connectToStream()
    .subscribe(
      tweet => {
        this.tweets.push(tweet);
      },
      error => this.errorMessage = <any>error
    );
}

當我將tweets聲明為any的數組時: tweets: any[] = []; 在我的AppComponent類的頂部,一切正常。 但是,我希望tweets屬於Tweet類型,所以tweets: Tweet[] = [];

進行此更改時,我得到錯誤Argument of type '{}' is not assignable to parameter of type 'Tweet' 實際上,當我將鼠標懸停在上面的代碼的第4行上的tweet上時,它的類型為{} 如何解決此問題,使tweets可以是Tweet對象的數組?

在您的訂閱中,投射每個項目的類型

    subscribe(
      (tweet as Tweet) => {
        this.tweets.push(tweet);
      },
      error => this.errorMessage = <any>error
    );

暫無
暫無

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

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