A-Level. React. TypeScript.

TypeScript

Теми

  1. Переваги
  2. Типи
  3. Функції
  4. Class

TypeScript

TypeScript is JavaScript with syntax for types

Астановлення

npm install typescript --save-dev

Ініціалізація

tsc --init - створює файлік tsconfig.json з налаштуваннями компілятора

Налаштування

В package.json створюємо скрипт для запуска компілятора
            "scripts": {
              "compile": "tsc ./index.ts",
              "watch": "tsc ./index.ts --watch"
            },
        

Типи

            const a: number = 1;
            const b: string = 2;
            const c: boolean = false;
            const arr: number[] = [1,2,3,4];
            const arr1: string[] = ['a', 'b', 'c', 'd'];
            let userInfo: [string, number];
            enum Color { Red, Green, Blue }
            enum HTTPCodes { Success = 200, ClientError = 400, ServerError = 500 }
        

Функції

            function add(a: number, b: number): number {
              return a + b;
            }
            let result1 = add(1, 2);
        
            function getFullName(firstName: string, lastName?: string) {
              if (lastName)
                return firstName + " " + lastName;
              else
                return firstName;
            }
        

Функції

            // описує контракт
            type FuncType = (baseValue: number, incrementValue: number) => number;
             
            const increase = <FuncType>function (x:number, y: number): number {
              return x + y;
            }
             
            const otherIncrease: FuncType = (x, y) => x + y;
        

Класси

            class User {
              id: number;
              name: string;
              getInfo(): string {
                return "id:" + this.id + " name:" + this.name;
              }
            }
        

Модифікатори доступу

            class User {
              public name: string;
              protected year: number;
              private: inn: number;
              readonly numberOdLegs = 8;
            }
        

Generics

            const logging = function<T>(arg: T): T {
              // send Data to log
              return arg
            }
            
            const logString: string = log<string>('str');
            const logNumber: number = log<number>(1);
        

Links