LeColor
LeColor

Reputation: 3

Cant understand functions parameters

Im learing typescript right now, and some friend, who works everyday with typescript, sent me some example code to try to crack it. But it seems like i cant get my head around it ...

The problematic part for me to understand is this:

{name, surname, age, gender}:iData = {}, object = object, like what ???

interface someData{
    name:string;
    surname?:string;
    age:number;
    gender?:"male" | "female";
}

function parseData({name, surname, age, gender}:iData = {}) {}

But when i try to run this code, compiler gives me error "type, {} is missing following properties" ... where is the problem ?

edit: Full error : Type '{}' is missing the following properties from type 'iData': name, age 7 function doSomething({name, surname, age, gender}:iData = {})

Upvotes: 0

Views: 41

Answers (1)

Maciej Sikora
Maciej Sikora

Reputation: 20132

The problem is that empty object {} does not fulfill interface with mandatory fields like in your example - age and name. In other words someData type does not include empty object value. To have it working you need to or have all properties optional or set up default name and age inside default value like:

function parseData({name, surname, age, gender}:iData = {name: '', age: 0}) {
}

To be clear I don't think you should set here any default, as clearly setting age to some example value will pop up in some code part after as a bug. I would not set here any default and argument will be required, but still above should solve your problem.

Upvotes: 2

Related Questions