TypeScript glossary

Note Statistics

Note Statistics

  • Viewed 168 times
Sun, 12/27/2020 - 14:33

Here is a short list of common typescript terms

In the snippet above we have a variable named greetingMessage defined as string using a type annotation. This would help the compiler to prevent us from assigning the incorrect type to our variables.

Polymorphic this

The polymorphic this is required when the return type needed is the current class of the target object. This is used commonly to facilitate chaining.

class Animal {
   setName(name: string): this {
	    this.name = name;

class Dog {
   bark(): this {
			return this;

class Cat {
   meow(): this {
			return this;

const dog = new Dog();
dog.setName('Doggy') // return type is Dog

const cat = new Cat();
cat.setName('Pearl') // return type is Cat

In the snippet above, depending on the class the return type on object.setName() is different. This the power of using Polymorphic this.

Type Annotation

This is the way to define a type for a variable. We add a type annotation to a variable by placing a colon after the variable name, followed by the data type of the variable. Additionally we can add a type annotation to a function to define the return type of that function. This is done by adding a colon (:) after the parentheses that surrounds the parameters, followed by the return type of the function.

let greetingMessage: string = 'Hello word';

function getGreetingMessage() : string {
  return 'Hello'

Type Inference

When the type of a variable is not defined, the compiler infers the type of the variables based on the

  • type of the values assigned to a variable
  • or the type of the value returned by a function.
let myString = 'this is a string'; // infered as a string
myString = 100; // error!!!

function myFunction() {
  return 12; // typescript inferes that the return type of myFunction is a number because of the type of the return value, a number

myString = myFunction(); // error because we are assigning a number to a string

Authored by