TypeScript - Objects

TypeScript

In this tutorial we will learn about objects in TypeScript.

If we want to create an object in JavaScript we write the following code.

var user = {
  username: 'Yusuf Shakeel',
  points: 10
};

In the above code we have created an object by the name user and the object has two properties username and points having string and number values respectively.

In TypeScript we can create the object in a similar way.

let user = {
  username: 'Yusuf Shakeel',
  points: 10
};

The only difference in the above code is that the type of user object is now assumed by TypeScript to be the following.

{ username: string, points: number }

That is, TypeScript expects user object to have two properties. And the first property name must be username and of type string and the second property name must be points and of type number.

So, if we try to reassign some other value to user then it will give us error during compilation.

The following code will not work.

// creating an object
let user = {
  username: 'Yusuf Shakeel',
  points: 10
};

// now assigning a new value
// this will give error
user = {
  name: 'Yusuf Shakeel',
  score: 10
};

On compiling we get the following error.

$ tsc
script/objects.ts(12,3): error TS2322: Type '{ name: string; score: number; }' is not assignable to type '{ username: string; points: number; }'.
  Object literal may only specify known properties, and 'name' does not exist in type '{ username: string; points: number; }'.

Object type

Following is a syntax to create an object type.

let varName: { prop1: type1, ...};

Where, varName is the name of the variable. The type of the variable is set as an object that takes prop1 as property and accepts value of given type type1 and so on.

In the following example we are creating an object type to store username, points and description.

// declaring variable of object type
let user: { username: string, points: number, description: string };

We can now assign an object value to the user variable like the following.

// assign value
user = {
  username: 'yusufshakeel',
  points: 9,
  description: 'This is my profile.'
};

Creating a complex object type

In the following example we are creating an object type that takes two numbers and also has a function to return back the sum of the numbers.

let obj: { x: number, y: number, getSum: () => number };

So obj object has three properties. The first two properties are of type number and the third one is an Arrow Function that takes no argument but returns a value of type number.

Now we can assign a value to the obj variable.

// assign value
obj = {
  x: 10,
  y: 20,
  getSum: function (): number {
    return this.x + this.y;
  }
};

// call the function getSum()
console.log("Sum: " + obj.getSum());