To add types to the object properties using the interface
declaration, we can start by first writing the keyword interface
followed by the name you want to give to the interface and then the {}
symbol (open and closed curly brackets).
Inside the brackets, we can type out the name of the property followed by the :
symbol (colon) and then the type you want to assign to the property and finally to end the property type declaration we can use either the ;
symbol (semi-colon) or the ,
symbol (comma).
TL;DR
// Person interface
interface Person {
name: string;
age: number;
}
// a simple object with properties
// with interface Person added
let person: Person = {
name: "John Doe",
age: 23,
};
To understand it a little better, let's say we have an object called person
with properties called name
and age
with values of John Doe
and 23
respectively like this,
// a simple object with properties
let person = {
name: "John Doe",
age: 23,
};
This is fine. But what if we want to have much more strictness over the types each property should hold. To do that, let's use the interface
declaration in TypeScript.
First, let's declare an interface
called Person
(NOTE: don't get confused between the object person
and interface Person
) and add types for each of the properties the person
object is going to hold.
In our case, the name
property should have a value of string
type and the age
property should have a value of number
type.
It can be done like this,
// Person interface
interface Person {
name: string;
age: number;
}
// a simple object with properties
let person = {
name: "John Doe",
age: 23,
};
Now, let's add interface Person
to the person
object. An interface
is added to object after variable name followed by :
symbol (colon).
It can be done like this,
// Person interface
interface Person {
name: string;
age: number;
}
// a simple object with properties
// with interface Person added
let person: Person = {
name: "John Doe",
age: 23,
};
Now we have a more strict and typed person
object which is exactly what we need. Yay 🎉!
See the above code live in codesandbox.
That's all 😃!