user20002028
user20002028

Reputation:

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

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.

Upvotes: 4

Views: 21515

Answers (4)

Naeem Akhtar
Naeem Akhtar

Reputation: 1270

One way you can try to make the variable optional with ? mark.

interface IData {
createdAt?: string;
currentUser?: string;
uniqueId?: string;

}

Upvotes: 0

Francisco Gomez
Francisco Gomez

Reputation: 11

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.

Upvotes: 1

Anjan Talatam
Anjan Talatam

Reputation: 4044

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:""
 }

Upvotes: 8

mikrowdev
mikrowdev

Reputation: 376

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

Upvotes: 2

Related Questions