【发布时间】:2022-11-21 00:01:02
【问题描述】:
我有一个函数可以从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。
【问题讨论】:
标签: javascript reactjs typescript compiler-errors