Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: Type '{}' is missing the following properties from type

interface Person {
  name: string;
  surname: string;
}
let person1: Person = {};

person1.name = "name"
person1.surname = "surname"

When I declare person1 I get this error:

Type '{}' is missing the following properties from type Person

like image 852
Acdn Avatar asked Dec 10 '22 01:12

Acdn


2 Answers

This is a better way:

let person1: Person = {name: '', surname: ''};

But if you want exactly empty object than you can hack it like this:

let person1: Person = {} as Person;

Update after comment:

Look at this unpredictableFunction:

const unpredictableFunction = (): string|number|string[] => {
  return Math.random() > 0.5 ? 'string' : Math.random() > 0.5 ? 9999 : ['1', '2', '3']
};

It may return number or it may return string or it may return array of strings

const person: Person = {name: '', surname: ''};
person.name = unpredictableFunction (); // this is a case you are talking about

In this case you will see

Type 'string | number | string[]' is not assignable to type 'string'.

Answers are:

Look at your code and ensure that you assign only strings to a Person properties,

Or update interface to be ready to a different values:

interface Person {
  name: string | number | string[];
  surname: string; 
}
like image 91
qiAlex Avatar answered Dec 14 '22 22:12

qiAlex


You have defined an interface with two required properties. So when you define an object with the type of the Person interface you must define these properties right away like this:

let person: Person = {
    name: '',
    surname: ''
}

However if you believe these properties are not required but are rather optional you can change your interface to this:

interface Person {
    name?: string;
    surname?: string;
}

Using the ? syntax you mark the property as optional. The following code should then work:

let person: Person = {};
like image 41
Mathyn Avatar answered Dec 15 '22 00:12

Mathyn