Javascript - Typescript

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > Javascript - Typescript

1 - About

TypeScript is a typed superset of JavaScript that compile to plain JavaScript. It adds static typing.

Advertising

3 - Basic

See Typescript - Compiler (tsc)

When installing third party libraries (lodash, jQuery, …), it is important to remember to install the typing definition for that library.

4 - JQuery

  • Add Jquery as package dependency (because it's already available we declare it as peer dependency)
yarn add @types/jquery --dev
yarn add jquery --peer
  • Add it to the compile path
tsconfig.json
{
  "compilerOptions": {
....
    "types": [
      "jquery"
    ]
  },
...
}

5 - Scope

  • Window: declare variable in the window scope
// Declare global constant
declare global {
    interface Window {
        ezConsentCategories:any;
        __ezconsent: any;
    }
}

6 - Feature

6.1 - Type

type annotation

Example:

  • : string is a type annotation that set the type string to the variable person
greeter.ts
function greeter(person: string) {
    return "Hello, " + person;
}

More … Basic Type

Advertising

6.2 - Enum

export enum choice {
  YES = 'Yes',
  NO = 'No',
  NA = 'Not applicable',
}

6.3 - Interface

person.ts
interface Person {
    firstName: string;
    lastName: string;
}
person.ts
function greeter(person: Person) {
    return "Hello, " + person.firstName + " " + person.lastName;
}
  • Then create an object of this type and calling the typed function
person.ts
let user = { firstName: "Jane", lastName: "User" };
document.body.textContent = greeter(user);

6.4 - Cast

level: loglevel.LogLevelDesc = <loglevel.LogLevelDesc> level

6.5 - Class

Classes in TypeScript are just a shorthand for the same prototype-based OO

Example:

  • a Student class with a constructor and a few public fields. public is a shorthand that creates properties from the argument with the same name. The class has then 4 properties (fullName, firstName, middleInitial and lastName).
student.ts
class Student {
    fullName: string;
    constructor(
        public firstName: string, 
        public middleInitial: string, 
        public lastName: string
     ) {
        this.fullName = firstName + " " + middleInitial + " " + lastName;
    }
}
  • As the Person interface share the same property names than the Student, a Student is also a Person
person.ts
interface Person {
    firstName: string;
    lastName: string;
}
let user = new Student("Jane", "M.", "User");
  • And can be used in every function expecting a Person.
student.ts
function greeter(person: Person) {
    return "Hello, " + person.firstName + " " + person.lastName;
}
document.body.textContent = greeter(user);
Advertising