TypeScript Objects

Learn via video courses
Topics Covered

Overview

Typescript is Javascript code with strictly typed language. Javascript runs on template-based code snippets, one may build objects without defining classes by using Object Literals and function Object() methods. An object is an instance that includes a collection of key-value pairs. The values can be scalars, functions, or arrays of other objects.

Introduction

Key-value pair form is represented by an object in TypeScript. If we have a little typescript object that we want to manage without building a model or plain old Java object (POJO) class in TypeScript, we may use typescript objects to construct a key and assign it to a value. They are convenient to use and simple to comprehend.

Different types may be used to form typescript objects, and they function in TypeScript just like any other declared and used variable. In the following part, we'll go into more depth about additional typescript objects and examine how to use them effectively when programming.

Objects in JavaScript can perform one of two tasks :

  • Records :
    A predetermined number of properties that were known at the time of development. Different types may exist for each characteristic.
  • Dictionary :
    A collection of properties whose names are unknown at the time of development. Both the property values and the property keys (strings and/or symbols) have the same type.

We shall first investigate typescript objects as records.

Syntax

We must provide values within them as key-value pairs, and as we have shown, they are quite simple and convenient to use. Let's look at its straightforward syntax for usage and comprehension below.

As you can conclude from the code above, we are just establishing a straightforward variable and setting a key-value pair to it. Let's practice some syntax to make things clear.

We shall go into further depth about its internal operation and the declaration of additional types inside objects in the following section.

How do Objects Function in TypeScript?

As we already know, declaring an object in TypeScript is identical to declaring any other variable. However, there is one distinction in that we may now give our variable within the typescript object a 'key'.

We may access them using the name 'key' once the typescript object has been created. In TypeScript, we can easily define an array, call our function inside the typescript object, declare still another object, etc. It is not required that we may just provide the text or integer type because TypeScript allows all other types as well.

This typescript object carries the data from an entity or request components similarly to the Java POJO classes. For that, we construct a model in TypeScript, but if we have a tiny typescript object that we wish to utilize only within one class, we may use the object instead in TypeScript.

Let's try declaring several functions, arrays, and another object in TypeScript inside the already existing object, as seen below.

1. Functions :

Just like any other values we declare below, we may declare our functions inside of them.

Code :

We are utilizing a function within the object in the code above. It is quite easy to memorize this syntax.

2. Array :

In the object instance, we can also declare an array as seen below.

Code :

The code above declares an array inside the object instance, making the above code and array very straightforward to utilize and understand. After that, we may use the 'key' name to retrieve this array.

Typescript Object value access :

We may use the name of the value to directly access it (array and function) inside the object. However, make sure it is accurate and included in the object, otherwise, a runtime error will result. Let's use the following instance.

Code :

Types of Objects in TypeScript

Two distinct broad categories of objects exist :

Uppercase-only thing All instances of class Object are of type "O" :

All non-primitive values have the type object, which is denoted by a lowercase "o" :

The qualities of an object can also be used to describe it :

TypeScript's Object v/s Object

Objects vs. Instances of Objects in Plain JavaScript

There is a crucial difference in simple JavaScript. On the one hand, Object is the class of most objects.

That implies :

  • They have prototype chains that contain Object.prototype :

  • They acquire its attributes.

On the other side, we may also make objects whose prototype chains do not contain Object.prototype. For instance, there is absolutely no prototype for the following item :

The object sample2 is not an instance of the class Object.

TypeScript Objects (Uppercase "O") are Instances of the Class Object

All instances of the class Object in TypeScript have the type Object. It has two interfaces that define it :

  • The attributes of the Object.prototype are defined by the interface Object.

  • The attributes of class Object are defined by the interface ObjectConstructor (i.e., the object pointed to by that global variable).

The attributes of interface Object are inherited by all instances of Object. If we design a function that returns its parameter, we can see that: When an instance of Object is entered, it always fulfills the return type, necessitating the need for a method. toString().

TypeScript Object (Lowercase "o") : Non-primitive Values

The object is the type for all non-primitive values in TypeScript (primitive values are booleans, numbers, undefined, null, bigints, and strings). We are unable to access any value's properties using this type.

Object vs. Object : Primitive Values

Remarkable would be that primitive values are included in type Object :

Why? Object.prototype's attributes are also accessible through basic values :

In contrast, primitive values are not included in an object :

Incompatible Property Types for Object vs. Object

When an object has a property whose type disagrees with the equivalent property in interface Object, TypeScript raises an error with type Object :

Since the type object has no attributes and hence cannot have any conflicts, TypeScript does not raise an error :

Optional Properties

The attributes that are not required are known as optional properties. The name of the person or thing in the example below is normally required, but the age is optional. The compiler throws an age is absent in a type error when we build a person object without providing a value for age. We must designate the property as optional to address this issue.

We frequently work with optional object attributes. For instance, only certain of our Person records may have phone numbers and different address data. These characteristics can be represented by a union type like string | undefined.

Each property, including the string | undefined ones, need a value when we construct a Person object. A type error occurs if any of the attributes are left out.

The verbosity makes the code more challenging to read. Thankfully, TypeScript offers an elegant, clear answer in the form of optional property types. We change phoneNumber: string to phoneNumber?: string by inserting a question mark. After that, we may remove the attribute from our objects. If we try to access the property without including it, we will receive an undefined.

But how does that function in practice? How did the undefined value get there if we never provided a value for phoneNumber? Undefined may show when we attempt to access an optional property such as phoneNumber?:. The type we get back represents this possibility : phoneNumber's true type is string | unknown. If we try to save a phoneNumber in a string variable, we will get the following error :

TypeScript Optional Property Generation

Typescript Objects :

Type Alias :

Interface :

Class :

Optional Property and Undefined

Age becomes an optional attribute when? is added. When trying to retrieve the age's value, undefined results are as expected.

Even though age is a number, typescript also enables us to provide an optional attribute with an undefined value.

This is due to the way TypeScript considers optional properties, which are treated as a union type of assigned and undefined types.

Index Signatures

When the values of the typescript object are of consistent kinds, the type of the object or dictionary is represented by the index signature.

Syntax :

Let's say we have a theme object that enables us to set the color preferences that may be applied to the entire application. The values will match the typed string exactly. This presents the ideal chance for us to use the index signature.

A string may be used to access a JavaScript object (and, by extension, a TypeScript object) and hold a reference to any other JavaScript object.

Here is a short example :

Under the 'key' Hello, we store the string Sahil. As we previously stated, it can store any JavaScript object, so let's save an example class object to demonstrate the idea :

Also, keep in mind that we indicated a string might be used to access it. The JavaScript runtime calls .toString on any additional object you supply to the index signature before receiving the result.

Keep in mind that every time the object is used in an index position, the function toString() will be called.

Arrays differ a little bit. JavaScript virtual machines will strive to optimize for number indexing (depending on things like whether it is an array and do the structures of items stored match etc.). Therefore, a number should be regarded as a legitimate object accessor in and of itself (distinct from the string). Here is a straightforward array example :

That's JavaScript, then. Let's now examine TypeScript's elegant treatment of this idea.

TypeScript Index Signature

First off, TypeScript will throw an error to save newcomers from shooting themselves in the foot because JavaScript simply uses the function toString() on any object index signature :

Because the default function toString() implementation on an object is so terrible (on version 8, for example, it always returns [object Object]), the user is required to be specific.

Naturally, the number is supported since

  • good Array / Tuple support needs it.
  • Its default function toString() method is great even if you use it for an obj (not [object Object]).

Point 2 is shown below :

String or integer must be used as the type of TypeScript index signature.

TypeScript accepts and supports symbols as well. Let's hold off on going there for now. little steps

An Index Signature Declaration

Therefore, we have been telling TypeScript to allow us to do anything we want by using any. An explicit index signature can be specified. For instance, let's imagine you want to ensure that everything contained in an object that uses a string adheres to the structure "message: string". The declaration { [index:string] : {message: string} } can be used to do this. The following illustrates this :

The name of the index signature, such as index in { [index:string] : {message: string} } is just important for readability and has no bearing on TypeScript. For instance, if it's usernames, you may type { [username:string] : {message: string} } to assist the developer who looks at the code after you (which just might happen to be you).

Of course, number indexes are also available, as seen by the following example: {[count: number]: SomeOtherTypeYouWantToStoreEgRebate}

Example : Object Literal Notation

The same code will be generated in JavaScript upon compilation.

Output :

TypeScript Type Template

Say you wrote an object literal in JavaScript using the following syntax :

JavaScript gives you the ability to modify an object in case you wish to give it some more value. This is how you would add a function to the person object later, if necessary.

The compiler generates an error if the identical code is used in Typescript. This is so that Typescript can recognize that concrete things have a typical template. Typescript objects must be an instance of a certain type.

By utilizing a method template in the declaration, you may resolve this.

Example : Typescript Type Template

The same code will be generated in JavaScript upon compilation.

Output :

Functions also accept objects as arguments/parameters.

Example : Objects as Function Parameters

An object literal is declared in the example. The person object is passed when calling the function expression.

It will produce the following JavaScript code after compilation.

Output :

Example : Anonymous Object

It will produce the following JavaScript code after compilation.

Output :

Duck-typing

If two objects have the same set of attributes, they are regarded as belonging to the same type in duck-typing. Duck-typing checks the items' eligibility by confirming that specific properties—rather than their precise type—are present. The following sentence often explains the concept :

"I call a bird a duck when it walks like a duck, swims like a duck, and quacks like a duck."

The duck-typing approach is implemented by the TypeScript compiler, enabling on-the-fly object generation while maintaining type safety. The example that follows demonstrates how to send objects to a function that doesn't explicitly implement an interface but yet has all the necessary members.

Example

Object-specific Rules and Regulations

There are currently no restrictions or rules governing objects. However, some standards must be adhered to, see below.

  1. Use a comma to separate each new value after the previous one.
  2. Braces should be used to enclose the object.
  3. We may use their 'key' as references to get the values.
  4. The object must include the 'key' before using it. Otherwise, a runtime error stating that a certain property is unknown would occur.

Conclusion

  • Aside from primitives, the most common types you'll encounter are most likely object types.
  • In instances where you need to generate an object dynamically, use the Record utility type or the object index signature to specify the object's permissible attributes.
  • As we now know, objects are relatively simple to use and, if necessary, may take the role of model objects.
  • The various objects have also been covered in great depth. To use them, only a keyword has to be used before the object name.
  • All values other than primitive values are represented by the TypeScript object type.
  • However, the Object type defines features that are present in all objects.
  • An object without any inherent properties is referred to as having the empty type{}.
  • Typescript Template Types are built on top of Literal Types to provide you with much more flexibility when defining types.
  • JavaScript's duck typing is designed in TypeScript via structural typing.
  • Since types are not "sealed", values that may be assigned to your interfaces may contain additional characteristics not included in your type declaration.