我有一個函式可以從rawData(來自 API)生成結構化資料
function makeData(raw:typeof rawData){
const data:IData = {} // this line throws above error.
const now = new Date()
data.createdAt=now.toDateString();
data.currentUser=raw.name;
data.uniqueId= raw.id now.toDateString();
return data
}
在制作資料時,我在開始時使用了一個空物件并使用 IData 鍵入它,以便函式的回傳值鍵入為IData. 但如前所述,這是拋出錯誤。
interface IData {
createdAt:string;
currentUser:string;
uniqueId:string;
}
用法:
const {createdAt, currentUser,uniqueId} = makeData(rawData)
我試圖完全洗掉 IData 然后我收到以下錯誤。
Property 'createdAt' does not exist on type '{}'. // got the same error for other properties as well ( currentUser, uniqueId )
在完成破壞的行上出現相同的錯誤。
我現在有一個解決方法:
const data : Record<string,unknown>= {}
但這對我來說似乎并不更有說服力。
有沒有更好的方法將資料鍵入為 IData。
現場演示。
uj5u.com熱心網友回復:
你不能在IData不指定其中資料的情況下定義 const of,相反你可以做這樣的事情
function makeData(raw: typeof rawData): IData{
const now = new Date()
return {
createdAt: now.toDateString(),
currentUser: raw.name,
uniqueId: raw.id now.toDateString()
}
}
uj5u.com熱心網友回復:
在這里,您將資料注釋為IData. 它期望物件包含所有必需的屬性。(在這種情況下:createdAt、currentUser、uniqueId)
你可以做兩件事。
1:你可以做型別斷言。
const data = {} as IData.
2:用空值初始化物件。
const data:IData = {
createdAt:"",
currentUser:"",
uniqueId:""
}
uj5u.com熱心網友回復:
需要定義物件的屬性
const data:IData = {
createdAt:'',
currentUser:'',
uniqueId:''
}
并為方法添加回傳型別
makeData(raw:typeof rawData): IData { ...
uj5u.com熱心網友回復:
發生這種情況是因為IData中的所有屬性都是必需的,因此如果您定義IData型別的變數,則需要為其提供值
也許您可以使用 UtilityType Partial或定義您要回傳的型別
function makeData(raw: typeof rawData): IData { }
@mikrowdev 的評論是我認為的最佳解決方案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/536981.html
上一篇:如何在反應js中移動串列中的專案
下一篇:將物件陣列傳遞給子組件
