TypeScript - Objects



An object in TypeScript is an instance which contains set of key value pairs. The key value pairs are also referred as object properties. The values can be scalar values or functions or even array of other objects. If a property's value is a function, that property is known as method.

Syntax

The syntax to create an object in TypeScript is given below −

var object_name = { 
   key1: "value1", //scalar value 
   key2: "value",  
   key3: function() {
      //functions 
   }, 
   key4:[ "content1", "content2"] //collection  
};

As shown above, an object can contain scalar values, functions and structures like arrays and tuples.

Type Annotations

In TypeScript, we should annotate the object properties as follows –

let person: {name: string, age: number} = {
   name: "Tom Hanks",
   age: 35,
}

In the above example we annotated the properties name and age of the person object.

We can also use interface to create type for object properties. Look the below example –

interface PersonType {
   fullname: string;
   age: number
}
var person: PersonType = { fullname:"Tom Hanks", age:32 };

Object Literal Notation

The object literal notation is the easiest way to create an object in TypeScript. We use curly braces ({}) to create object. Each property of the object is separated by a comma. Each property is written as property name (key) followed by colon (:) followed by property value.

Example

In the example below, we have created an object named person containing two properties. The first property is firstname: "Tom" and the second property is lastname: "Hanks". We access the property values and print them in console.

var person:{ firstName: string, lastName: string}= { 
   firstName:"Tom", 
   lastName:"Hanks" 
}; 
//access the object values 
console.log(person.firstName) 
console.log(person.lastName)

On compiling, it will generate the following code in JavaScript.

var person = {
    firstName: "Tom",
    lastName: "Hanks"
};
//access the object values 
console.log(person.firstName);
console.log(person.lastName);

Output

Tom 
Hanks

TypeScript Type Template

Let's say you created an object literal in JavaScript as −

var person = { 
   firstname:"Tom", 
   lastname:"Hanks" 
};

In case you want to add some value to an object, JavaScript allows you to make the necessary modification. Suppose we need to add a function to the person object later this is the way you can do this.

person.sayHello = function(){ return "hello";}

If you use the same code in Typescript the compiler gives an error. This is because in Typescript, concrete objects should have a type template. Objects in Typescript must be an instance of a particular type.

You can solve this by using a method template in declaration.

Example: Typescript Type template

var person = {
   firstName:"Tom", 
   lastName:"Hanks", 
   sayHello:function() {  }  //Type template 
} 
person.sayHello = function() {  
   console.log("hello "+person.firstName)
}  
person.sayHello()

On compiling, it will generate the same code in JavaScript.

Output

The above generated JavaScript code will produce the following output -

hello Tom

Objects as Function Parameters

Objects can also be passed as parameters to function.

Example: Objects as function parameters

var person = { 
   firstname:"Tom", 
   lastname:"Hanks" 
}; 
var invokeperson = function(obj: { firstname:string, lastname :string }) { 
   console.log("first name :"+obj.firstname) 
   console.log("last name :"+obj.lastname) 
} 
invokeperson(person)

The example declares an object literal. The function expression is invoked passing person object.

On compiling, it will generate following JavaScript code.

//Generated by typescript 1.8.10
var person = {
   firstname: "Tom",
   lastname: "Hanks"
};

var invokeperson = function (obj) {
   console.log("first name :" + obj.firstname);
   console.log("last name :" + obj.lastname);
};

invokeperson(person);

Output

first name :Tom 
last name :Hanks

Anonymous Objects

You can create and pass an anonymous object on the fly.

Example: Anonymous Object

var invokeperson = function(obj:{ firstname:string, lastname :string}) { 
   console.log("first name :"+obj.firstname) 
   console.log("last name :"+obj.lastname) 
} 
invokeperson({firstname:"Sachin",lastname:"Tendulkar"});

On compiling, it will generate following JavaScript code.

//Generated by typescript 1.8.10
var invokeperson = function (obj) {
   console.log("first name :" + obj.firstname);
   console.log("last name :" + obj.lastname);
};

invokeperson({ firstname: "Sachin", lastname: "Tendulkar" });

Output

first name :Sachin 
last name :Tendulkar

Duck-typing

In duck-typing, two objects are considered to be of the same type if both share the same set of properties. Duck-typing verifies the presence of certain properties in the objects, rather than their actual type, to check their suitability. The concept is generally explained by the following phrase −

“When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.”

The TypeScript compiler implements the duck-typing system that allows object creation on the fly while keeping type safety. The following example shows how we can pass objects that don’t explicitly implement an interface but contain all of the required members to a function.

Example

interface IPoint { 
   x:number 
   y:number 
} 
function addPoints(p1:IPoint,p2:IPoint):IPoint { 
   var x = p1.x + p2.x 
   var y = p1.y + p2.y 
   return {x:x, y:y} 
} 

//Valid 
var newPoint = addPoints({x:3,y:4},{x:5,y:1})  

//Error 
var newPoint2 = addPoints({x:1},{x:4,y:3})
Advertisements