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
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;
}
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 = {};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With