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 string
, number
, bigint
, boolean
, undefined
, symbol
, 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.
Table of Contents
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
1 2 3 4 5 6 7 8 9 10 | let person = { firstName: "Allie", lastName: "Grater", age: 50, fullName: function() { return this.firstName + " " + this.lastName; } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | let item:any; //any type //assign a object item = { id:1, name: "Samsung Galaxy" } console.log(item.name) //ok //Accessing non existant property. No compiler error console.log(item.price); //ok //You can assign a new object to same variable item = {firstName: "Allie", lastName: "Grater"} //ok //Accessing non existant property. No compiler error console.log(item.name) //ok |
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.
1 2 3 4 5 6 7 | { "compilerOptions": { "noImplicitAny":true } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | let item; //noImplicitAny is set to true //assign a object item = { id:1, name: "Samsung Galaxy" } console.log(item.name) //ok item.firstName=""; //Compiler error console.log(item.firstName); //Compiler error //But You can assign a new object to same variable item = {firstName: "Allie", lastName: "Grater"} console.log(item.firstName) //ok item.name=""; //Compiler error console.log(item.name) //Compiler error |
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
.
1 2 3 4 5 6 | { id:number; name:string } |
We can assign the object type to a variable by annotating it with :type
after the variable name as shown below
1 2 3 4 5 6 7 | let item : {id:number, name:string} //Annotating with the type item = { id:1, name: "Samsung Galaxy" } //Assigning a value console.log(item.name) //ok |
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.
1 2 3 4 5 6 7 8 | console.log(item.price) //compiler error //Property 'price' does not exist on type '{ id: number; name: string; }'. item = { id:1, name: "Samsung Galaxy", price:100 } //compiler error //Type '{ id: number; name: string; price: number; }' is not assignable to type '{ id: number; name: string; }'. |
You can also assign the object directly, in this case, Typescript infers and automatically assigns the correct type to the variable
1 2 3 4 5 6 7 8 9 10 11 12 13 | let item = { id:1, name: "Samsung Galaxy" } console.log(item.name) //ok console.log(item.price) //compiler error //Property 'price' does not exist on type '{ id: number; name: string; }'. item = { id:1, name: "Samsung Galaxy", price:100 } //compiler error //Type '{ id: number; name: string; price: number; }' is not assignable to type '{ id: number; name: string; }'. |
Hovering the mouse over the item variable will show the inferred object type of the item variable
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.
1 2 3 4 | let item1 : { id:number, name:string} let item2 = { id:1, name: "Samsung Galaxy" } |
The calculate function below accepts a qty
and an anonymous object with id
, name
& price
property.
1 2 3 4 5 | function calculate(qty:number, item: { id:number, name: string , price:number }):number { return qty * item.price; } |
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.
1 2 3 4 5 6 7 8 9 10 11 | let item : { id:number, name:string, price:number} item = { id:1, name: "Samsung Galaxy", price:100 } console.log(calculate(10, item)); //1000 function calculate(qty:number, item: { id:number, name: string , price:number }):number { return qty * item.price; } |
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
.
1 2 3 4 5 6 7 | type product = { id:number; name:string ; price:number } |
Once you have a name for the type, you can use it everywhere you want to use that type.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | type product={ id:number; name:string ; price:number } let item :product item = { id:1, name: "Samsung Galaxy", price:100 } console.log(calculate(10, item)); //1000 function calculate(qty:number, item: product):number { return qty * item.price; } |
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.
1 2 3 4 5 6 7 | interface product { id:number; name:string ; price:number } |
Once we have the interface defined, we can use it just like any other type.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | interface product { id:number; name:string ; price:number } let item :product item = { id:1, name: "Samsung Galaxy", price:100 } console.log(calculate(10, item)); //1000 function calculate(qty:number, item: product):number { return qty * item.price; } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | class Product { id:number; name:string ; price:number; constructor(id:number, name:string,price:number) { this.id=id; this.name=name; this.price=price; } } let item :Product item = new Product(1,"Samsung Galaxy", 100); //create a new product console.log(calculate(10, item)); //1000 function calculate(qty:number, item: Product):number { return qty * item.price; } |
References
Read More