Skip to content

TypeScript

TypeScript is a programming language developed by Microsoft as a superset for JavaScript. Angular is built on TypeScript, which can be seen from the characteristic extension of its logic files: *.ts.

TypeScript developers needed a tool that would strengthen JS's weaknesses. They believed JS was average for writing larger applications. They noticed emerging scalability and maintenance issues with such programs.

TypeScript adds to JavaScript, among others strong typing and compiles to readable, standards-based JavaScript.

TypeScript vs JavaScript

JavaScript is a dynamic scripting language used to create interactive applications, so it is not intended for complex applications, although this changes with successive versions of ECMAScript. TypeScript, on the other hand, is a static scripting language that is a superset of JavaScript, which means it is an extra layer on top of JS code. TypeScript was not designed to replace Javascript. In fact, it never replaces existing behavior. It uses existing JS behaviors to overcome its limitations.

Javascript TypeScript
let foo = 5; let foo: number = 5;
let bar = "SDA"; let bar: string = "SDA";
let anyData = 123; let anyData: any = 123;
let list = [1, 2, 3]; let list: Array<number> = [1, 2, 3];
function square(a) function square(a: number): number

Advantages of TypeScript

  • Simplifies JavaScript code, making it easier to read and debug.
  • Offers all the benefits of [ES6 +] (https://www.w3schools.com/Js/js_es6.asp) and greater work efficiency.
  • Strong typing that facilitates, among others refactoring code and catching errors.
  • Saves developers time.
  • Extends JavaScript classes and introduces interfaces.
  • Ability to use namespaces (modules).
  • Ability to compile to a JavaScript version that works on all browsers.
  • Helps you implement SOLID design patterns into a language that doesn't really support it.
  • With Dependency Injection testing becomes easier.

Basic data types

As the name of the language suggests, everything in TypeScript relates to types. This makes the code more scalable and reliable, and the developer can check that the code is working correctly.

To assign a type in TypeScript, you need a colon (:), a type name, an equal sign (=), and a variable value.

Boolean

let isActive: boolean = true;

Number

As in JavaScript, all [numbers] (../../HTML_CSS_JS/JavaScript/data types/number.md) have one type.

let age: number = 26;
let gravity: number = 6.67;

String

let foo: string = 'Ala has a cat';
let bar: string = 'Ala has a cat named ' + catName;
let baz: string = `Ala has a cat ${catName}`

Array

In TypeScript, arrays are a collection of the same type of objects. They can be declared in two ways: either with a data type followed by [], or with the general array approach Array <ObjectType>.

let myArray: number[] = [1, 2, 3];
//OR
let myArray: Array<number> = [1, 2, 3];

Any

In some situations, not all types of information are available to the programmer and sometimes he may not fully know what type of data will be returned by an external API, for example. In such cases, type checking can be dispensed with, just like in normal JavaScript, only consciously here.

let unknown: any = 4;

Void

This is a callback type that can be replaced by various other types as needed. Void is used when the function returns no value.

function showAlert(text: string): void {  
  alert(text);
}

Enum

It allows you to define a set of named and predefined constants. They are defined with the enum keyword. You can define a numeric or string value.

enum Day {
  Monday,
  Tuesday,
  Wednesday,
  Thursday,
  Friday
}

let d: Day = Day.Monday; //d = 0

Tuple

It allows you to define an array with a fixed number of elements whose types are known but do not have to be the same.

let tuple: [number, string] = [10, 'hello'];  

It is worth noting, however, that a similar effect can be obtained using the array:

let array: (number | string)[] = [10, 'hello'];  

Functions

TypeScript does not make any major changes to the Javascript core where functions reside. The only difference is the strong typing of the function parameters and the return type.

function greeter(person: string): string {
  return 'Hello, ' + person;
}

let user: any = [0, 1, 2];

document.body.textContent = greeter(user); //❌ Argument of type 'number []' cannot be assigned to type 'string'.

Interfaces

Interfaces are a mechanism for naming complex variable types and using them just like base types.

In the following example, the compiler will check if the object passed to the greeter() function has a firstName and a lastName field:

interface Person {
  firstName: string;
  lastName: string;
}

function greeter(person: Person): string {
  return 'Hello, ' + person.firstName + " " + person.lastName;
}

let user = { firstName: 'Jan', lastName: 'Kowalski' };

document.body.textContent = greeter(user);

Classes

Definition of a class it is very similar to Java and C # and may contain the following elements:

  • Properties - a property/field is any variable declared in the class.
  • Constructor - a special kind of method that is called when an object is created.
  • Methods - methods represent actions that an object can take.
class Greeter {
  greeting: string;

  constructor(message: string) {
    this.greeting = message;
  }

  greet() {
    return "Hello, " + this.greeting;
  }
}

let greeter = new Greeter("world");

Encapsulation of class objects

A class can control the visibility of its objects to other classes. The default visibility level is public.

Public - free and unlimited access

class Person {
  fullName: string; //Identical to "public fullname: string"
  constructor(public firstName: string, public lastName: string) {
    this.fullName = firstName + " " + lastName;
  }
}

Private – access only inside the classroom

class Person {
  private fullName: string;
  constructor(private firstName: string, private lastName: string) {
    this.fullName = firstName + " " + lastName;
  }

  public getFullName() {
    return this.fullName;
  }
}

let person = new Person('John', 'Smith');
person.getFullName(); //✅ OK
person.fullName; //❌ 'fullName' is private;

Protected – access from the extension class

class Person {
    protected fullName: string;
    constructor(protected firstName: string, protected lastName: string) {
        this.fullName = firstName + " " + lastName;
    }
}

class Student extends Person {
  private index: number;

  constructor(firstName: string, lastName: string, index: number) {
    super(firstName, lastName);
    this.index = index;
  }

  public getIndex() {
    return this.index;
  }

  public getFullName() {
    return this.fullName; //✅
  }
}

let student = new Student('John', 'Smith', 12345);
student.getIndex(); //✅
student.fullName; //❌ field is of 'protected' type
student.firstName; //❌ is of 'protected' type

TypeScript, like other object-oriented languages, uses the extends keyword for class inheritance. In the above code, the class Person is the base class and the class Student is the derived class (Student inherits fromPerson). Conversely, the function super() enables a derived class to call a constructor from a base class.

Note the use of the keywords public/private/protected on arguments in the constructor. This is a kind of shortcut that allows you to automatically create a property with that name and a specific access modifier.