DEV Community

Cover image for TypeScript Basics
Jovana Marčeta
Jovana Marčeta

Posted on

TypeScript Basics

TypeScript is superset to JavaScript. TypeScript adds optional types to JavaScript that support tools for large-scale JavaScript applications. TypeScript compiles to readable and standard-based JavaScript. Angular embraces TS.

Installing TypeScript

If we want to be able to install TypeScript globally, there is a CLI command:

npm install -g typescript
Enter fullscreen mode Exit fullscreen mode

If we want to be able to use TypeScript as dependency on specific project there is also command. When we run it, it will create json files and node modules.

npm install typescript --save-dev
Enter fullscreen mode Exit fullscreen mode

Compiling TypeScript File

We create file with .ts extension. But it is not enough, we need to invoke TypeScript compiler. TypeScript code needs to be compiled to Vanilla JavaScript to be able to run in the browser. After successful compilation, we will get Vanilla JavaScript version of TS file. If there are errors, we will be notified in terminal.

To be able to do it we need TypeScript configuration file to be able to compile all our TS files. Result is tsconfig.json file, where we have many options (like strict type checking mode). Angular has this file by default.

npx tsc --init
Enter fullscreen mode Exit fullscreen mode

To be able to watch for changes that we made and apply them immediately, there is watch mode:

npx tsc --watch
Enter fullscreen mode Exit fullscreen mode

Primitive Types Examples

Add static types in TypeScript is not difficult. Bellow is syntax for variable with number, string and boolean type declaration. If we pass value of different type, TS will throw and error:

let mark: number = 9;
let firstName: string = 'John';
let hasPassport: boolean; 
Enter fullscreen mode Exit fullscreen mode

Reference Types Examples

If we want to have array of string, we use square brackets:

let cars: string[]; 
cars = ['Audi', 'Cadilac', 'Honda'];
Enter fullscreen mode Exit fullscreen mode

We define which kind of type should be stored in object before adding values:

let student: {
    name: string;
    gpa: number;
};

student = {
   name: 'John',
   gpa: 8
};
Enter fullscreen mode Exit fullscreen mode

If we want to store an array of objects, TypeScript has syntax for that too:

let students: {
   name: string;
   gpa: number;
}[];
Enter fullscreen mode Exit fullscreen mode

But here we have next problem - we repeat our selves, code is not clean. We can fix this using type alias to avoid repeating. It is pure TypeScript feature.
First, we define Type alias:

type Student = {
   name: string;
   gpa: number;
}
Enter fullscreen mode Exit fullscreen mode

Next, we set object type and what value should it take:

let student: Student;

student = {
    name: 'John',
    gpa: 8
};

let students: Student[];
Enter fullscreen mode Exit fullscreen mode

Union Types

You want to your variable be able to take multiple types? No worries, there are union types:

let password: string | number | boolean = 'abc';
password = 999;
Enter fullscreen mode Exit fullscreen mode

We can hold an array of strings too:

let data: string | string[]; 
Enter fullscreen mode Exit fullscreen mode

Type Inference

TypeScript have important feature and that is Type Inference. It help us write less and more cleaner code.

When we declare a variable TS sees which type we store and it will use that type as main type. So, if we try to declare another type it will throw an error. So, we don't need to add a type, we stich with type inference as much as possible.

Functions

We can add types to function. Functions even have types for return values and we can define it.

function add(a: number, b: number): number {
    return a + b;
}
Enter fullscreen mode Exit fullscreen mode

There is possibility to use union type of function return type:

function add(a: number, b: number): number | string {
    return a + b;
}
Enter fullscreen mode Exit fullscreen mode

There is special type called void. Void means that function don't return anything. Any property means that any type is allowed.

function printOut(something: any) { 
    console.log(something)
}
Enter fullscreen mode Exit fullscreen mode

TypeScript Classes

In the code example bellow is defined class, with reduced code:

class Car {
    constructor(
        public model: string,
        public color: string,
        public seatsNumber: number,
        public features: string[]
    ) {}

    addFeature(feature: string) {
       this.features.push(feature);
   }
}

const car1 = new Car('BMW5', 'red', 4, ['Sunroof', 'Backup camera', 'Navigation system']);

car1.addFeature('Bluetooth');
Enter fullscreen mode Exit fullscreen mode

Interfaces

Interfaces are object typed definitions. They exists in most static typed programming languages. But they are not available in Vanilla JavaScript, so TypeScript is there to help. And is worth to mention that interfaces are not compiled.

First we define structure of any object that we wanna create. For methods (functions inside object) we just add type. Void type means that it returns nothing.

interface Animal {
    breed: string;
    age: number;

    sayHello: () => void;
}

let rex: Animal;

rex = {
    breed: 'German Sharpeid',
    age: 3,
    sayHello() {
        console.log('AW AW');
   }
}
Enter fullscreen mode Exit fullscreen mode

If we want our class to implement features from Interface, that class will be forced to use features defined in Interface correctly, so we are able to get certain advantage. We have to add all properties as we can see in example below:

class WildAnimals implements Animal {
  breed: string;
  age: number;
  sayHello() {
      console.log('rrr');
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)