TypeScript tutorial: Lesson 14 – Object


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: {keyA:valueA},  
   key3: function() {
      //function body
   }, 
   key4: ["val1", "val2"], //collection  
   key5: ["val3", {keyB:valueB}]
};

Example:

var person = { 
   name:"Tom", 
   age:18
}; 
//access the object values 
console.log(person.name) 
console.log(person.age)

Result:

[LOG]: Tom 
[LOG]: 18 

Object as function parameter

Example: with interface:

interface Iperson {
   name:string
   age:number
}
var person:Iperson = { 
   name:"Tom", 
   age:18
}; 
function myFunc(obj:Iperson):void { 
   console.log("name :"+obj.name) 
   console.log("age :"+obj.age) 
} 
myFunc(person)

Result:

[LOG]: name :Tom 
[LOG]: age :18 

Example: without interface:

var person = { 
   name:"Tom", 
   age:18
}; 
function myFunc(obj:{name:string,age:number}):void { 
   console.log("name :"+obj.name) 
   console.log("age :"+obj.age) 
} 
myFunc(person)

Example: Object are passed by reference

var person = { 
   name:"Tom", 
   age:18
}; 
function changePerson(obj:{name:string,age:number}):void { 
   obj.name="Peter"
   obj.age=20
} 
changePerson(person)
console.log("name :"+person.name) 
console.log("age :"+person.age) 

Result:

[LOG]: name :Peter 
[LOG]: age :20 

Object destructuring

Syntax:

var {key1,key2} = object_name

Example

var job = {_name:"Job", salary:1000}
var {_name,salary} = job
console.log(_name,salary)

After comliping:

"use strict";
var job = { _name: "Job", salary: 1000 };
var _name = job._name, salary = job.salary;
console.log(_name, salary);
 

Result:

[LOG]: Job,  1000 

Leave a Reply