Relying on Type Inference
Below is the most basic way of defining an object in TypeScript. The person
object in this code example is defined without any type annotations. TypeScript will automatically infer that the name
property is of type string
and the age
property is of type number
, based on their initial values.
const person = {
name: 'Harry',
age: 22,
};
// Printing the entire object
console.log(person);
// Printing a property of an object
console.log(person.name);
Console Logs
{name: "Harry", age: 22}
Harry
Explicit Type Annotations
To make the types of the properties a bit more strict, we can be explicit on the data type.
Let's take a look at the example below. The person2
object is defined with explicit type annotations for its properties. This makes the code more explicit and can improve readability, but it also requires more typing and can be less flexible if the types of the properties change in the future.
// Specifying property types of an object
const person2: {
name: string;
age: number;
} = {
name: 'Hermione',
age: 23,
};
// Printing the entire object
console.log(person2);
// Printing a property of an object
console.log(person2.name);
Console Logs
{name: "Hermione", age: 23}
Hermione
Nesting Objects
It is possible to nest objects as well. Below is an example:
// Nesting an object
const person3 = {
name: 'Ron',
age: 21,
education: {
school_name: 'Hogwarts',
house: 'Gryffindor',
year: 3,
},
};
console.log(person3.education);
console.log(person3.education.school_name);
Console Logs
{school_name: "Hogwarts", house: "Gryffindor", year: 3}
Hogwarts
View Parent Post: TypeScript: Everything You Need to Know