TypeScript Objects Tutorial

In this TypeScript tutorial we learn how to create standalone objects. We cover how to create object literals and how to instantiate an object with a constructor method.

We also learn about the 'this' keyword, how to define methods within standalone objects, and how to pass objects to other functions.

Lastly, we take a look at the list of Object methods available in TypeScript.

How to create standalone objects

Because Javascript is template based, we can create objects in TypeScript directly, instead of needing classes first.

There are 2 ways to create objects.

  • Object Literals
  • Instantiating an object with a constructor method and new

note We should compile the following scripts with the compiler flag --target es6 or greater.

How to create an object literal

We create an object literal by assigning a code block to a variable.

Inside the code block, we add the property, followed by a colon operator and the value we want to assign to it. If we define multiple properties, they’re separated with a comma.

Syntax:
let object_name = {
  property: value,
  property: value
}
Example:
let person = {
  firstName: "John",
  lastName: "Doe",
  age: 29
}

We access the properties through dot notation, using the object’s name.

Example:
let person = {
  firstName: "John",
  lastName: "Doe",
  age: 32
}

console.log("Name: " + person.firstName + " " + person.lastName)
console.log("Age: " + person.age)

How to instantiate a new object with a constructor method

A constructor is a function that initializes the object with values we specify.

note An object constructor is a little bit different than a class constructor, which we discuss in the tutorial lesson about class constructors .

First, we need to create a function with all the properties we want to initialize when the object is instantiated, as function parameters.

Syntax:
 function constructor_name(property1, property2, ...) {}

Inside the function we assign the parameters to properties in the object. To do this, we have to specify the this keyword, which refers to the calling object.

tip The variables and parameters may have the same names.

Syntax:
function constructor_name(property1, property2, ...) {
  this.property1 = property1
  this.some_property_name = property2
}

Anything we pass to the constructor as an argument, will be assigned to the property of the object.

The this keyword references the calling object. We can just imagine the this keyword being replaced by whatever we name our object.*

To instantiate an object with the constructor we create a new instance, as we did before. However, this time we pass the values we want between the parentheses to assign them to the properties of the object.

Syntax:
 let object_name = new constructor_name(argument1, argument2)

As with any other object, we access the properties through dot notation.

Example:
function person(first_name, last_name, age) {
  this.fn = first_name
  this.ln = last_name
  this.age = age
}

let p1 = new person("John", "Doe", 29)

console.log("Name: " + p1.fn + " " + p1.ln)
console.log("Age: " + p1.age)

How to define a method within a standalone object

We can define functions inside a standalone object. But, before we define the function, we must first create a variable with the same name as the function and refer to it with the this keyword.

Syntax:
function constructor_name() {
  this.method_name = function_name

  function_name() {
	// body
  }
}
Example:
function person(firstName, lastName, age) {
  this.fn = firstName
  this.ln = lastName
  this.age = age

  // function template
  this.walk = walk
  // function itself
  function walk() {
    console.log("Walking...")
  }
}

let p1 = new person("John", "Doe", 29)

p1.walk()

How to pass an object to a function as parameter

We can pass an object to a function as an argument, but we should also add the properties we want available to that object.

To do that, we start by defining a parameter name, followed by a colon as if we want to add a type. After the colon we create a code block, and within the code block we specify the properties we want from the object.

Syntax:
let object_name {
	property_name: property_value
}

function func_name(obj_param: { property_name: property_type } ): return_type {
	// use obj_param.property
}
Example:
let person = {
  firstName: "John",
  lastName: "Doe",
  age: "32",
}

function logPerson(obj: { firstName: string, lastName: string, age: string } ): void {
  console.log("Name: " + obj.firstName + " " + obj.lastName)
  console.log("Age: " + obj.age)
}

// 'person' object literal
// as function argument
logPerson(person)

The code won’t break if we don’t specify the properties, but we want to add them explicitly to know exactly how the function can behave. It’s the whole purpose of TypeScript.

Example:
let person = {
  firstName: "John",
  lastName: "Doe",
  age: "32",
}

function logPerson(obj) : void {
  console.log("Name: " + obj.firstName + " " + obj.lastName)
  console.log("Age: " + obj.age)
}

// 'person' object literal
// as function argument
logPerson(person)

List of Object methods

The following list of methods are available to objects in TypeScript.

MethodsDescription
assign()Copy enumerable and an object's properties from one object to another.
create()Create a new object with the specified prototype object and properties.
defineProperty()Create property.
defineProperties()Create or configure multiple properties.
entries()Return an array with arrays of the key, value pairs.
freeze()Prevent existing properties from being removed.
getOwnPropertyDescriptor()Return a property descriptor.
getOwnPropertyDescriptors()Return all property descriptors.
getOwnPropertyNames()Return an array of all properties.
getOwnPropertySymbols()Return an array of all symbol key properties.
getPrototypeOf()Return the prototype of the specified object.
is()Evaluate whether two values are the same.
isExtensible()Evaluate if an object is extensible.
isFrozen()Evaluate if an object was frozen.
isSealed()Evaluate if an object is sealed.
keys()Return an array of the object's own property names.
preventExtensions()Prevent the object from being extended.
seal()Prevent new properties from being added and mark all existing properties as non-configurable.
setPrototypeOf()Set the prototype of an object, to another object.
values()Return an array of values.

Summary: Points to remember

  • We don’t have to create classes to be able to create objects. We can create them directly by either creating object literals, or with a constructor method.
  • The this keyword in a constructor method refers to the calling object, the object that will be created from the constructor.
  • When passing an object to a function as a parameter, we should specify the object’s properties as well.