Home > Mobile >  Type '{}' is missing the following properties from type ts(2739)
Type '{}' is missing the following properties from type ts(2739)

Time:11-21

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.

CodePudding user response:

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()
    }
    
}

CodePudding user response:

Here as you are annotating data as IData. It expects the object to contain all the required properties. (in this case: createdAt, currentUser, uniqueId)

You can do 2 things.

1: You can do type assertion.

const data = {} as IData.

2: Initialise the object with empty values.

const data:IData = {
  createdAt:"",
  currentUser:"",
  uniqueId:""
 }

CodePudding user response:

Need to define the properties of the object

const data:IData = {
  createdAt:'',
  currentUser:'',
  uniqueId:''
 }

And add a return type to the method

makeData(raw:typeof rawData): IData { ...

CodePudding user response:

That's happen because all the propertys inside IData are required, so if you define a variable of type IData you need to provide it the values

Maybe you can use the UtilityType Partial or define what type are you going to return

function makeData(raw: typeof rawData): IData { }

The comment by @mikrowdev is the best solution for this i think.

  • Related