Table of contents
1.
Introduction
1.1.
What are objects in typescript?
1.2.
Syntax
2.
Property Modifiers in Objects
2.1.
Optional property
2.2.
Readonly property
3.
Declaring a variable that holds an object
4.
object Vs. Object in Typescript
5.
Empty type{} in Typescript
6.
Frequently Asked Questions
7.
Key Takeaways
Last Updated: Mar 27, 2024

Objects in TypeScript

Author Sneha Mallik
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Objects are the most fundamental method of grouping and passing data around in JavaScript. Object types are used to represent these in TypeScript. TypeScript can tell an object's shape and what member properties it has or doesn't have. If the code tries to access members of an object that doesn't exist, TypeScript will throw an error. It may even make suggestions for improvements.

What are objects in typescript?

The objects in typescript are a type of instance that consists of a collection of key-value pairs. Scalar values, functions, and even arrays of other objects can be used as values. The TypeScript object type represents all values that aren't in primitive types.

TypeScript has the following primitive types:

  • Number
  • String
  • Bigint
  • Null
  • Boolean
  • Undefined
  • Symbol

Syntax

The syntax for objects in typescript is as follows:

var objectName = { 
   key1: “value_1”, // value_1 is a scalar value 
   key2: “value_2”,  
   key3: function() {
      // functions to be mentioned here…
   }, 
   key4: [“content_1”, “content_2”] // collection  
};

As demonstrated above, an object can include scalar values, functions, and structures like arrays and tuples.

Property Modifiers in Objects

In an object type, each of the properties can specify the following:

  • The type
  • Whether the property is optional

Optional property

We'll be dealing with objects that have a collection of properties most of the time. Optional property is applicable when not all of an object's properties have been assigned values. Before the colon ':', insert a '?' symbol after the property name to indicate whether it is optional.

  • Whether the property can be written

Readonly property

For TypeScript, properties can also be marked as 'readonly'. A readonly property cannot be written to during type-checking, even though it has no effect at runtime. The readonly modifier does not always indicate that a value is completely immutable, i.e., its internal contents cannot be modified. It simply implies that the property cannot be rewritten.

Declaring a variable that holds an object

The following code demonstrates how to declare an object-holding variable:

let person: object;
person = {
   firstName: 'Sneha',
   lastName: 'Mallik',
   jobStatus: 'Student'
};

console.log(person);

Output:

We will get an error here if we try to reassign a primitive value to the person object:

let person: object;

person = "Ninja";
console.log(person);

Output Error:

The person object is a type of object that has a set of properties. If we try to access a property on the person object that doesn't exist, we'll get the following error:

let person: object;

person = "Ninja";
console.log(person.firstName);

Output Errors:

It's important to note that the above statement works correctly in JavaScript and instead returns undefined.

To explicitly describe properties of the person object, you must first declare the person object with the following syntax:

let person : {
  firstName: string;
  lastName: string;
  age: number;
  jobStatus: string;
};

The person object is then assigned to a literal object with the following properties:

person = {
  firstName: 'Harry',
  lastName: 'Potter',
  age: 30,
  jobStatus: 'At work'
};

Alternatively, we can use both syntaxes in the same statement, as shown here:

let person : {
 firstName: string;
 lastName: string;
 age: number;
 jobStatus: string;
} = {
  firstName: 'Harry',
  lastName: 'Potter',
  age: 30,
  jobStatus: 'At work'
};

object Vs. Object in Typescript

With the letter O in uppercase, TypeScript provides another type named Object. It's crucial to know how they vary.

All non-primitive values are represented by the object type, whereas all object functionality is described by the Object type.

For example: The function toString() and function valueOf() methods are accessible to any object of the Object type.

Empty type{} in Typescript

The empty type denoted by {} is a TypeScript type that is quite similar to the object type.

An object of the empty type is one that has no properties of its own. TypeScript will throw a compile-time error if we try to access a property on such an object:

let person: {};
person.firstName = 'Ninja';
console.log(person);

Output Errors:

However, we can use the prototype chain to access all the properties and methods declared on the Object type, which are available on the object:

let person: {}={};
console.log(person.toString());

Output:

Frequently Asked Questions

1. Explain what is meant by ‘object as a type’.

Ans:  'object' is a type of all non-primitive values in TypeScript. Primitive values are undefined, null, booleans, numbers, bigints, strings. We can't access any of the value's properties with this object type.

 

2. What are the general types of objects?

Ans: Objects can be divided into two categories:

  • All instances of class Object have the type Object with an uppercase "O":
let object1: Object;
  • The type of all non-primitive values is object with a lowercase "o":
let object2: object;

Objects can also be described through their properties- Object Type Literal and Interface. 

Key Takeaways

In this blog, we have learned the concepts of objects in typescript and how they are used with examples, syntax and working. The TypeScript object type represents any value that's not a primitive value. The Object type, on the other hand, describes the functionality that applies to all objects. An object of the empty type {} has no properties of its own.

Take a look at our Typescript archives section and see many more interesting topics related to it. Apart from that, you can refer to our Guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc.

Credits: GIPHY

Happy Developing!

Live masterclass