TypeScript - Objects


Advertisements

An object is an instance which contains set of key value pairs. The values can be scalar values or functions or even array of other objects. The syntax is given below −

Syntax

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.

Example: Object Literal Notation

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

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

The output of the above code is as follows −

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.

The output of the above code is as follows −

hello Tom

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);

Its output is as follows −

first name :Tom 
last name :Hanks

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" });
invokeperson({ firstname: "Sachin", lastname: "Tendulkar" });

Its output is as follows −

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