Issue
I have a function that makes structured data from rawData
(from 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
}
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.
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.
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.
Live Demo.
Solution
you can't define a const of IData
without specify the data inside of it, instead you can do something like this
function makeData(raw: typeof rawData): IData{
const now = new Date()
return {
createdAt: now.toDateString(),
currentUser: raw.name,
uniqueId: raw.id + now.toDateString()
}
}
Answered By - mikrowdev
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.