這個 typescript 函數應該適用於兩種不同類型的數組(即具有不同接口的數組),它們都有兩個共同的屬性(id 和 count)。該函數使用給定的 id 更新項目或任務的計數屬性。但是我在“查找”命令中收到打字稿錯誤:“表達式不可調用。” 如果我刪除其中一個接口,即如果我只將輸入參數“items”定義為一個項目數組 (Item[]) 或一個任務數組 (Task[]),它就可以工作。但我想將該函數應用於兩種類型的數組。
//interface definitions
export interface Item {
id: number,
count: number,
other: number
}
export interface Task {
id: number,
count: number,
more: string
}
//function
function UpdateCount(items: Item[] | Task[], id: number, count: number) {
let item = items.find(obj => obj.id === id);
if (item !== undefined) {
item.count = count;
}
}
我的解決方案是:
//interface definitions
interface BaseItem {
id: number,
count: number
}
export interface Item extends BaseItem {
other: number
}
export interface Task extends BaseItem {
more: string
}
//function
function UpdateCount<T extends BaseItem>(items: T[], id: number, count: number) {
const item = items.find(i => i.id === id);
if (!item) return;
item.count = count;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句