How To Create And Work With TypeScript Objects

How To Create And Work With TypeScript Objects

TypeScript objects are the go-to choice when you need to group different values into a single instance in object-oriented programming. We are going to show you how to create and modify them in your application.

TypeScript Objects

There are 7 primitive types for simple data in TypeScript, which are number, string, boolean, bigint, symbol, null, and undefined. In addition to them, TypeScript also supports object types, so you can create more complex types and data structures.

Like objects in JavaScript, they are collections of properties (which are, in turn, associations between a key and a value). The value of a property can be a value of another type or function. Any property can also be a nested property, meaning it contains a set of properties inside itself.

Creating Objects

With Object Literals

A TypeScript object literal is a set of properties separated by commas, all of which are stored in a pair of curly brackets.

This example illustrates how to write a simple object literal:

{
    name: 'John',
    age: 26,
    occupation: 'Software engineer'
};

It has three properties. The key of the first one is “name”, whose value is “John” (a string). Likewise, values of the second and the final properties are 26 and “Software engineer (a number and a string), respectively.

Your object literals can have just one or even zero properties:

{
    domain: 'learnshareit.com'
}
{}

You can assign these literals to names, making them objects:

let employee = {
    name: 'John',
    age: 26,
    occupation: 'Software engineer'
};

TypeScript will automatically infer the shape of the object for you, but you can also explicitly describe it:

let employee: {name: string; age: number; occupation: string;} = {
    name: 'John',
    age: 26,
    occupation: 'Software engineer'
};

While TypeScript can absolutely infer types from an object, there are times you want to declare them explicitly first without giving them specific values. This is how you can do this with the above object:

let employee: {
    name: string;
    age: number;
    occupation: string;
};

TypeScript now understands that the employee name is an object with three properties, whose types are string, number, and string, respectively.

Now you can initialize this objects by giving it values of all the properties:

employee = {
    name: 'John',
    age: 26,
    occupation: 'Software engineer'
}

Type Aliases

Your code may have a lot of objects with the same shape, meaning they have the same keys, including their names and types. Declaring each object live above would be tiring. You can declare an object type, and then create instances of this type instead.

You can use the type keyword to create a type alias. For example, we will create an object type for every employee in the whole company:

type Employee = {
    name: string;
    age: number;
    occupation: string;
};

Now Employee is an object type with three required properties. We can create an instance with this shape:

let a: Employee = {
    name: 'John',
    age: 26,
    occupation: 'Software engineer'
};

Interfaces

Interfaces are another option for declaring an object type. They are generally preferred over aliases thanks to their greater error readability, better class interoperability, and faster compilation performance.

The equivalent syntax for the above alias is as follows:

interface Employee {
    name: string;
    age: number;
    occupation: string;
};

Optional Properties

By default, every declared property is strictly required by TypeScript. For example, if you create an object of the Employee type without giving a value for any properties, the compiler will complain about it:

let b: Employee = {
    name: 'John',
};

Output

Type '{ name: string; }' is missing the following properties from type 'Employee': age, occupations

To avoid these errors, you can create optional properties. You can choose to give values to them or not, depending on the particular object.

You can indicate a property is optional by inserting a question mark before the colon in the type annotation:

interface Employee {
    name: string;
    age?: number;
    occupation?: string;
};

Now the declaration with the name b above won’t result in errors anymore.

Read-Only Properties

The readonly modifier blocks any attempt to reassign the value of a property. You can make a property read-only by placing this keyword before its normal type annotation:

interface Employee {
    readonly name: string;
    age: number;
    occupation: string;
};

In this example, the property name of an object will be locked after it has been assigned the initial value. Trying to change its value later will result in errors:

let a: Employee = {
    name: 'John',
    age: 26,
    occupation: 'Software engineer'
};

console.log(a.name);
a.name = 'George';
console.log(a.name);

Output

Cannot assign to 'name' because it is a read-only property.

Keep in mind that this protection doesn’t exist in the JavaScript code the compiler produces. That language doesn’t support type-checking. The read-only nature of the property is only adhered to by TypeScript during development.

Object Operations

Access Properties

You can now access values of this object’s properties and modify them:

console.log(employee.name);
employee.name = 'George';
console.log(employee.name);

Output

John
George

In addition to the dot notation, you can also use the square brackets:

console.log(employee['name']);
employee.name = 'George';
console.log(employee['name']);

Delete Properties

You can delete optional properties with the delete operator:

interface Site {
    name?: string;
}

let main: Site = {
    name: 'LearnShareIT'
}

console.log(main.name);
delete main.name;
console.log(main.name);

Output

LearnShareIT
undefined

Note: TypeScript will raise a warning when you try to delete a non-optional property, even though it will still compile your code.

Compare Objects

Even when two different objects have the same shape and values, comparing them with the equality operators will always yield false:

let site1 = {
    name: 'LearnShareIT'
}

let site2 = {
    name: 'LearnShareIT'
}

console.log(site1 === site2);

Output

false

Extending Types

From a base object type, you can create another type based on it with more properties. You will have to use the extends keyword for this.

Example

interface Employee {
    name: string;
    age: number;
    occupation: string;
};

interface Executive extends Employee {
    title: string;
}

In this example, we extend the object type Employee and create the Executive type with the title property in addition to all the existing properties of Employee.

You can combine multiple types by extending them into a new object type:

interface Phone {
    os: 'string';
}

interface TouchScreen {
    size: number;
}

interface Device extends Phone, TouchScreen {};

Tutorials

Learn more about TS Objects in the article below:

Summary

You can give TypeScript objects a shape with object literals, aliases, or interfaces. They allow you to define the types of properties in your objects or create object types, to group data like JavaScript objects.

Leave a Reply

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