tsc --init //создаём файл tsconfig.json

https://metanit.com/web/typescript/2.4.php

В TypeScript имеются следующие базовые типы:

  • Boolean: логическое значение true или false
  • Number: числовое значение
  • String: строки
  • Array: массивы
  • Tuple: кортежи
  • Enum: перечисления
  • Any: произвольный тип
  • Null и undefined: соответствуют значениям null и undefined в javascript
  • Void: отсутствие конкретного типа

Так, на первой строке компилятор TS увидит, что переменной присваивается строка, поэтому для нее будет использоваться тип string.

Псевдонимы типов

type stringOrNumberType = number | string;
let sum: stringOrNumberType = 36.6;
if (typeof sum === "number") {
    console.log(sum / 6);
}

Type assertion

let someAnyValue: any = "hello world!";
let strLength: number = (<string>someAnyValue).length;
console.log(strLength); // 12

let someUnionValue: string | number = "hello work";
strLength = (<string>someUnionValue).length;
console.log(strLength); // 10

Вторая форма заключается в применении оператора as:

let someAnyValue: any = "hello world!";
let strLength: number = (someAnyValue as string).length;
console.log(strLength); // 12

let someUnionValue: string | number = "hello work";
strLength = (someUnionValue as string).length;
console.log(strLength); // 10

Если функция ничего не возвращает, то указывается тип void:

function add(a: number, b: number) {
    return a + b;
}
let result = add(10, 20);

Статические свойства и функции

class Operation {

    static PI: number = 3.14;

    static getSquare(radius: number): number {

        return Operation.PI * radius * radius;
    }
}
let result = Operation.getSquare(30);
console.log("Площадь круга с радиусом 30 равна " + result);
let result2 = Operation.PI * 30 * 30;
console.log(result2);   // 2826

Наследование классов

class User {

    name: string;
    constructor(userName: string) {

        this.name = userName;
    }
    getInfo(): void {
        console.log("Имя: " + this.name);
    }
}

class Employee extends User {

    company: string;
    work(): void {
        console.log(this.name + " работает в компании " + this.company);
    }
}

let bill: Employee = new Employee("Bill");
bill.getInfo();
bill.company = "Microsoft";
bill.work();

Переопределение базовых классов

class User {

    name: string;
    constructor(userName: string) {

        this.name = userName;
    }
    getInfo(): void {
        console.log("Имя: " + this.name);
    }
    getClassName(): string {
        return "User";
    }
}

class Employee extends User {

    company: string;
    constructor(employeeCompany: string, userName: string) {

        super(userName);
        this.company = employeeCompany;
    }

    getInfo(): void {
        super.getInfo();
        console.log("Работает в компании: " + this.company);
    }
    getClassName(): string {
        return "Employee";
    }
}

let tom: User = new User("Tom");
tom.getInfo();
console.log(tom.getClassName());

let alice: User = new Employee("Microsoft", "Alice");
alice.getInfo();
console.log(alice.getClassName());

let bill: Employee = new Employee("Google", "Bill");
bill.getInfo();
console.log(bill.getClassName());

// результаты
// Имя: Tom
// User
// Имя: Alice
// Работает в компании: Microsoft
// Employee
// Имя: Bill
// Работает в компании: Google
// Employee

results matching ""

    No results matching ""