Learn TypeScript

Creating object types

Creating object types

In this lesson, we will learn how we can create strongly-typed objects.

Inferred object types

Let's explore object types in an exercise.

TypeScriptOpen exercise in CodeSandbox

The code assigns tomScore to an object with name and score properties.

🤔

What has TypeScript inferred the type of tomScore to be?

Object types are denoted with curly brackets. Each member of the object is listed inside the curly brackets with its type annotation.

🤔

So, later in the program, if we change the score property value, to the following, will TypeScript be happy with this?

tomScore.score = 75;
🤔

What about if we try to add a new property to the object later in the program?

tomScore.passed = true;

Using explicit object type annotations

We can explicitly specify the annotation on an object variable using the object notation like was inferred in the example above:

let variable: { member1: type1; member2: type2, ... };
  • In the code editor, explicitly set the type for tomScore using a type annotation.
  • Make the score property in the object optional and remove score from the object in the assignment.

Summary

TypeScript can infer the type of an object from the assigned value. If the inferred type is not quite what we require, we can explicitly use an object type annotation.

What if we want to reuse an object type instead of redefining it each time? Is there a way to do this? Yes, there are several ways! We’ll learn these in the following lessons.

© 2024 Carl Rippon
Privacy Policy
This site uses cookies. Click here to find out more