题意:
类型 '{}' 缺少类型 ts(2739) 中的以下属性。
问题背景:
I have a function that makes structured data from rawData
(from API)
我有一个函数可以将来自 API 的 rawData
转换为结构化数据
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
}
As I am making the data, I am using an empty object in the beginning and typing it with IData so that the return value from the function is typed as IData
. But as mentioned this is throwing error.
翻译为:
在构造数据时,我一开始使用一个空对象并将其类型设置为 `IData`,这样函数的返回值就会被标记为 `IData`。但如前所述,这导致了错误。
interface IData {
createdAt:string;
currentUser:string;
uniqueId:string;
}
Usage:
const {createdAt, currentUser,uniqueId} = makeData(rawData)
I tried to remove IData completely then I got the following error.
我尝试完全移除 IData
,然后出现了以下错误
Property 'createdAt' does not exist on type '{}'. // got the same error for other properties as well ( currentUser, uniqueId )
Getting the same error(s) on the line where destructing is done.
在进行解构赋值的那一行上也出现了相同的错误。
I got a workaround for now:
我现在找到了一种变通方法
const data : Record<string,unknown>= {}
But this doesn't seem to be more convincing for me.
但这似乎对我来说并不令人信服
Is there a better way to type data as IData.
有没有更好的方法将数据类型为 `IData`?
Live Demo.
问题解决:
you can't define a const of IData
without specify the data inside of it, instead you can do something like this
你不能在不指定数据的情况下定义 `IData` 的常量,而是可以这样做:
function makeData(raw: typeof rawData): IData{
const now = new Date()
return {
createdAt: now.toDateString(),
currentUser: raw.name,
uniqueId: raw.id + now.toDateString()
}
}