我有一个函数可以从 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。
直播Demo .
最佳答案
此处,您将数据注释为 IData
。它期望该对象包含所有必需的属性。 (在本例中:createdAt、currentUser、uniqueId)
你可以做两件事。
1:您可以进行类型断言。
const data = {} as IData.
2:用空值初始化对象。
const data:IData = {
createdAt:"",
currentUser:"",
uniqueId:""
}
关于javascript - 类型 '{}' 缺少类型 ts(2739) 的以下属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74509421/