我有兩個相同介面的物件:
interface Project {
_id?: string
title: string
description: string
goal: string
tasks?: Task[]
createdAt?: Date
updatedAt?: Date
}
一個包含上述所有欄位,另一個應包含部分或全部:標題/描述/目標。
我只想為相關鍵分配第二個到第一個,并且只有在存在有效值的情況下。
到目前為止我得到了什么:
const updateProjectUtil = (target: Project, update: Project): Project => {
Object.keys(update).forEach(key => {
const k = key as keyof Project;
if (target.hasOwnProperty(k) && update[k]) {
target[k] = update[k] // this line get a typescript error
}
})
return target;
}
我收到一個錯誤:
鍵入'字串 | 任務[] | 日期 | undefined' 不可分配給型別 'string & Task[] & Date'。型別“未定義”不可分配給型別“字串 & 任務 [] & 日期”。型別“未定義”不可分配給型別“字串”。
我嘗試使用 Object.entries 但它似乎沒有任何效果。
更大的圖景:我正在使用 Node.js 和 Express 構建一個 RESTful API。這屬于更新路由的控制器,它從客戶端獲取更新物件和從資料庫(MongoDB)獲取目標物件,更改它需要的欄位并將資料保存到資料庫后回傳客戶端。
我該怎么做才能讓它發揮作用?謝謝。
uj5u.com熱心網友回復:
當我試圖運行你的代碼時,我得到了另一個錯誤。不確定您的問題是否有誤,但下面的代碼對我有用:
type Task = {
name: string
}
interface Project {
_id?: string
title: string
description: string
goal: string
tasks?: Task[]
createdAt?: Date
updatedAt?: Date
}
const updateProjectUtil = (target: Project, update: Project): Project => {
let result = { ...target }
Object.keys(update).forEach(key => {
const k = key as keyof Project;
const updatingValue = update[k]
if (target.hasOwnProperty(k) && updatingValue) {
result = { ...result, [k]: updatingValue }
}
})
return result;
}
我還將函式更改為不修改輸入引數target,因為無論如何您都回傳它
uj5u.com熱心網友回復:
嘗試
interface Project {
[key: string]: unknown // indexable
_id?: string
title: string
description: string
goal: string
tasks?: Task[]
createdAt?: Date
updatedAt?: Date
}
我認為這缺少索引簽名。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/439212.html
