![](/img/trans.png)
[英]error TS2322: Type 'string | null' is not assignable to type 'number'
[英]error TS2322: Type 'number' is not assignable to type 'string'
我正在嘗試構建一個應用程序,我想首先按用戶獲取我的帖子,然后在單擊帖子時,我想按 id 獲取此特定帖子。
最后我收到以下錯誤:
src/app/cars/car-detail/car-detail.component.ts(25,11) 中的錯誤:錯誤 TS2322:類型 'Observable<{ _id: string; 標題:字符串; 內容:字符串; 圖像路徑:字符串; 創建者:字符串; }>' 不能分配給類型 'Car[]'。
'Observable<{ _id: string; 類型中缺少屬性'includes' 標題:字符串; 內容:字符串; 圖像路徑:字符串; 創建者:字符串; }>'。
src/app/cars/car-detail/car-detail.component.ts(26,11): 錯誤 TS2322: 類型 'number' 不能分配給類型 'string'。
import { Input, Component, OnInit } from '@angular/core';
import { Car } from '../car.model';
import { CarsService } from '../cars.service';
import { ActivatedRoute, Params } from '@angular/router';
@Component({
selector: 'app-post-detail',
templateUrl: './post-detail.component.html',
styleUrls: ['./post-detail.component.css']
})
export class PostDetailComponent implements OnInit {
@Input() post: Post[] = [];
@Input() id: string;
constructor(
private postsService: PostsService,
private route: ActivatedRoute
) { }
ngOnInit() {
this.route.params
.subscribe(
(params: Params) => {
this.post = this.postsService.getPost(this.id);
this.id = +params['id'];
}
);
}
}
我該怎么辦?
@Input() id: string
的類型是string
,但是,當這樣做this.id = +params['id'];
- +
運算符嘗試將params['id']
解析為number
,所以為什么會出錯。
將@Input() id: string
類型設置為number
。
this.post = this.postsService.getPost(this.id);
因為我認為getPost
返回一個observable 。 您需要訂閱它,然后將調用返回的結果分配給post
屬性。
this.postsService.getPost(this.id).subscribe(res => this.post = res);
我在嘗試這個時遇到了類似的情況。
錯誤 TS2322:“數字”類型不可分配給“字符串”類型
以下是我在實現節點休息 api 時遇到的錯誤。
error TS2322: Type 'string' is not assignable to type 'number | FindOperator<number>'.
27 const product = await repository.find({ id: req.params.id });
我必須簡單地將變量類型從id:number
更改為id: string
。
此函數中使用的關聯變量在另一個文件中聲明。 該特定變量的聲明類型(在我的例子中它被命名為“id”)與產生錯誤的行的變量類型不兼容。
所以去聲明的地方,根據類型將變量類型設置為數字/字符串,然后它將與其余函數兼容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.