TypeScript
Переменные
let a: number = 1;a = "hello"; // Type 'string' is not assignable to type 'number'
Функции
function add(a: number, b: number): number { return a + b;}
Классы
class Person { name: string; constructor(name: string) { this.name = name; }}
let person = new Person("allen");
Перечисления
enum Color { Red, Green, Blue,}
let color: Color = Color.Red;
Массивы
let array: number[] = [1, 2, 3];
Type
type Person = { name: string; age: number;};
let person: Person = { name: "allen", age: 30,};
Типы данных
Тип | Описание |
---|---|
number | Число |
string | Строка |
boolean | Логический тип |
any | Любой тип |
void | Ничего |
Union
function showId(id: number | string) { console.log(id);}
showId(1);showId("1");
Optional
Function
function greet(firstName: string, lastName: string, patronymic?: string) { console.log(`Hello, ${firstName} ${lastName} ${patronymic}`);}
Class
class Person { firstName: string; lastName: string; patronymic?: string;
constructor(firstName: string, lastName: string, patronymic?: string) { this.firstName = firstName; this.lastName = lastName; this.patronymic = patronymic; }}
Type
type Person = { firstName: string; lastName: string; patronymic?: string;};
Абстрактные классы
abstract class PLayer { hp: number; speed: number; constructor(hp: number, speed: number) { this.hp = hp; this.speed = speed; }}
class CT extends PLayer { constructor(hp: number, speed: number) { super(hp, speed); }
defuse(): void { console.log("defuse"); }}
class T extends PLayer { constructor(hp: number, speed: number) { super(hp, speed); }
plant(): void { console.log("plant"); }}
Getter and Setter
class Student { fullName: string; private _mark: number; constructor(fullName: string, mark: number) { this.fullName = fullName; if (mark > 0 && mark <= 10) { this._mark = mark; } else { throw new Error("Mark must be between 0 and 10"); } }
get mark() { return this._mark; }
set mark(mark: number) { if (mark > 0 && mark <= 10) { this._mark = mark; } else { throw new Error("Mark must be between 0 and 10"); } }}
const student = new Student("Allen", 10);console.log(student.mark);student.mark = 15;console.log(student.mark);
Generics
function createPair<T, U>(a: T, b: T, c: U, d: U) { return [ [a, b], [c, d], ];}
class Student { fullName: string; marks: number[]; constructor(fullName: string, marks: number[]) { this.fullName = fullName; this.marks = marks; }}
class Teacher { fullName: string; subject: string; constructor(fullName: string, subject: string) { this.fullName = fullName; this.subject = subject; }}
const student1 = new Student("John Doe", [90, 95, 80]);const student2 = new Student("Jane Doe", [85, 90, 95]);
const teacher1 = new Teacher("John Smith", "Math");const teacher2 = new Teacher("Jane Smith", "English");
const pair = createPair(student1, student1, teacher1, teacher1);
console.log(pair);