I have an Interface Person
and I am able to create an object user1
of the type Person
by assigning all the properties at once
export interface person {
name: string;
age: number;
city: string;
}
let user1: person = {
name:"ron",
age: 22,
city:"AL"
}
Is there a way for me to build this object instead of assigning all the properties at once. Im am looking for something like this
let user2:person;
user2.age = 22;
user2.name = "Dave";
user2.city = "NY"
3
Answers
If you create a class that implements the interface you can set the default value of the properties to be empty
and then set them as you want later
One way around this is to declare an object with "empty" properties and then initialize them afterwards
You can use the type utility
Partial<Type>
when initializing the value to indicate that the properties have not yet been defined:After initializing the property values, TypeScript will correctly infer that they do indeed exist:
TS Playground
However, if you do not initialize one of the property values, TypeScript will emit an error diagnostic when trying to use it:
TS Playground
There are still some scenarios where the inference isn’t enough — for example, when the value needs to be used as an argument to a function which requires a
Person
:TS Playground
In these cases, you can create a function called a type guard which will check at runtime to ensure that the type meets the stated expectations. A user-defined type guard is a function whose return type is a type predicate:
Then you can check whether
user
actually meets the definition ofPerson
before using it in order to avoid errors:TS Playground