How to add types to object properties in TypeScript?

September 17, 2021 - 3 min read

To add types to object properties in TypeScript First, we can declare the variable name, followed by the : symbol (colon), followed by the {} symbol (Open and close curly brackets). Inside the brackets, we can define the name of the property followed by the : symbol (colon), and the type of property we want us to assign.

To end the type declaration we can either use the ; symbol (semi-colon) or the , symbol (comma).

TL;DR

// simple object
// with types added for each property
let personDetails: {
  name: string;
  age: number;
};

// allowed ✅
personDetails = {
  name: "John Doe",
  age: 23,
};

For example, let's say we have an object called personDetails having 2 properties called name and age like this,

// simple object
const personDetails = {
  name: "John Doe",
  age: 23,
};

As we can see from the above code that the name property holds a value of string type called John Doe and the age property holds the value of number type called 23.

This is fine. But this object is not strictly typed.

Currently, we can have any kind of values on either of the properties which may bring problems during the runtime of the program if not done properly.

Now let's try to enforce the types for both properties. The name property should only have values that are of type string and the age property should only have values that are of type number.

It can be done like this,

// simple object
// with types added for each property
let personDetails: {
  name: string;
  age: number;
};

// allowed ✅
personDetails = {
  name: "John Doe",
  age: 23,
};

As we can see that the TypeScript allowed us to have the values for each of the properties in the personDetails object because all the types are satisfied.

Now let's try to change the value of the name to another type other than the type string.

It can be done like this,

// simple object
// with types added for each property
let personDetails: {
  name: string;
  age: number;
};

personDetails = {
  name: 1, // not allowed ❌. Type 'number' is not assignable to type 'string'
  age: 23,
};

As you can see from the above code that the TypeScript compiler doesn't allow us to add the numeric value and will also show an error saying Type 'number' is not assignable to type 'string' which is what we want to happen.

See the execution of the above codes live in codesandbox.

That's all 😃!

Feel free to share if you found this useful 😃.