Objects & Object Type in TypeScript

In this tutorial, let us look at the objects and learn how to create the object type and assign it to objects. objects are the most fundamental data type in TypeScript. The Typescript has seven primitive data types stringnumberbigintbooleanundefinedsymbol, and null. Anything that is not a primitive data type is an object. Understanding objects and creating types to represent them is crucial in learning TypeScript. In this tutorial, we will learn what objects are in TypeScript and how to create types for objects and use them.

What is an object?

An object is a collection of key-value pairs. Each key-value pair is known as a property, where the key is the name of the property and value its value

Objects provide a way to group several values into a single value. You can group any values of other types like string, number, booleans, dates, arrays, etc. An object can also contain other objects. We can easily build a more complex structure using them.

Each key-value pair in the key-value collection is a property of the object. The TypeScript objects can have any number of properties. You can also create an empty object without any properties. The key or name of the property must be unique. The property name is string  (But can also be a symbol type). No two properties can have the same name. We store or retrieve the value of an object using its property name (key). Value can be any valid TypeScript value. For example string, number, date, function, or another object.

We can also assign a function to a property in which case the property is known as a method.

Creating Objects in TypeScript

There are a few ways in which you can create an object in TypeScript. One of the is to use the Object Literal Syntax. It consists of a list of key-value pairs, each separated by a comma and wrapped inside curly braces

Typescript Objects using object literal syntax

Objects without Type

We can create objects in TypeScript without assigning a type or using any type so as to opt out of type checking.

Objects with Explicit Any Type

When we assign any type explicitly to a variable, the Typescript compiler does not make type checking on the variable.

In the example, even though the item object does not have a price property, the compiler does not throw any errors. We can also assign a new object to the item object without getting any errors from the compiler.

Objects with Implicit Any Type

When we do not assign a type and TypeScript fails to infer its type from the assignment or from its usage, then the compiler assigns the type any to it. But how the compiler behaves depends on the noImplicitAny compiler option. You can enable or disable this in the tsconfig file.

noImplicitAny set to false

When set to false, the code behaves exactly in the same way as if you have an explicitly assigned type any. i.e. Typescript treats the variable as of type Any.

noImplicitAny set to true

When noImplicitAny is set to true, Typescript does not treat the variable as any. It now tries to infer the type at every usage of item variable.

In the example above we assign the item variable with an object consisting of id & name property. When we access the non-existent firstName property compiler throws an error.

But the compiler does not prevent us from assigning a new object to the item variable. Typescript compiler correctly identifies the new type and uses that to check the subsequent usage of the item variable.

Object Type

Typescript allows us to create types for objects and annotate the variable with that type. The object type consists of Key type pairs (instead of key value pairs which you see in an object) separated by either a comma or a semicolon.

The following is an example of an object type consisting of two properties. id property is of type number and name property is of type string.

TypeScript Object Literal

We can assign the object type to a variable by annotating it with :type after the variable name as shown below

With our item variable annotated with an object type, the compiler throws an error when we try to access a non-existent property or when we assign a new object which has a completely different type.

You can also assign the object directly, in this case, Typescript infers and automatically assigns the correct type to the variable

Hovering the mouse over the item variable will show the inferred object type of the item variable

TypeScript Object Type

Assigning Types to Objects

There are a few ways by which we can create an object with a concrete type for objects. They broadly fall into two categories. One is the Anonymous Type and the other one is the Named Type.

Anonymous Types

The Anonymous object types are types without any name. We create them on the fly.

The item1 & item2 variables in the following example give a type of object consisting of id & name property.

The calculate function below accepts a qty and an anonymous object with id, name & price property.

Anonymous Types are best when you do not need to re-use the type.

But take a look at the following example, where we created an item and passed it to the calculate method. We have used the type definition { id:number, name:string, price:number} twice. In such circumstances where we need to re-use the type again, then the better option is to use the named type.

Named Types

We can also name our object type, which allows us to re-use the type again and again. There are two ways in which you can name an object type in TypeScript. One is Type Alias and the other one is Interface.

Type Alias

The Type Aliases in Typescript allow us to give a custom name to an existing type. The syntax starts with the keyword type followed by the name you wish to give to the new type. It is then followed by an assignment operator and then the type literal.

The following example creates a type alias product.

Once you have a name for the type, you can use it everywhere you want to use that type.

Interface

An interface declaration is another way to name an object type. The syntax starts with the keyword interface followed by the name you wish to give to the interface. It is then followed by the type literal.

Once we have the interface defined, we can use it just like any other type.

Class

The class is an object-oriented programming (OOP) way to create objects in Typescript. The class definition contains the blueprint of what an object should look like.

The following is an example of the Product class. We create an instance of the Product by calling the new keyword followed by the class name.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top