Шпаргалка по TypeScript: освоение ключевых концепций и лучших практик
Установка, запуск, типы, классы, все основы
Содержимое страницы
Вот моя краткая шпаргалка по TypeScript, охватывающая ключевые концепции, синтаксис и примеры кода, часто используемые разработчиками:
Шпаргалка по TypeScript
Начало работы
- Установить глобально:
npm install -g typescript
- Скомпилировать файл:
tsc filename.ts
- Проверить версию:
tsc --version
Основные типы
let a: number = 10;
let s: string = "TypeScript";
let b: boolean = true;
let arr: number[] = [1, 2, 3];
let tuple: [string, number] = ["TS", 2025];
let anyValue: any = "Flexible";
let unknownVal: unknown = 5;
let notDefined: undefined = undefined;
let notPresent: null = null;
Объединение и литеральные типы
let id: number | string = 42;
let direction: 'left' | 'right' = 'left';
Псевдонимы типов и интерфейсы
type Point = { x: number; y: number };
interface Person { name: string; age: number; }
let user: Person = { name: "Alice", age: 25 };
Функции
function sum(a: number, b: number): number {
return a + b;
}
const multiply = (a: number, b: number): number => a * b;
function log(msg: string): void { console.log(msg); }
Классы
class Animal {
name: string;
constructor(name: string) { this.name = name; }
move(distance: number = 0): void { console.log(`${this.name} moved ${distance}`); }
}
Модификаторы доступа
public
(по умолчанию),private
,protected
,readonly
class Point {
constructor(private x: number, private y: number) {}
}
Обобщения
function identity(arg: T): T { return arg; }
let output = identity("myString");
Перечисления
enum ResourceType { BOOK, FILE, FILM }
let r: ResourceType = ResourceType.BOOK;
Приведение типов / Кастинг
let someVal: unknown = "Hello";
let strLength: number = (someVal as string).length;
Модули
// Экспорт
export function foo() {}
// Импорт
import { foo } from "./module";
Расширенные типы
- Пересечение:
type A = { a: number }; type B = { b: number }; type AB = A & B; // { a: number, b: number }
- Условный:
type IsString = T extends string ? true : false;
- Отображение:
type Readonly = { readonly [P in keyof T]: T[P]; }
- Тип шаблона строки:
type EventName = `on${Capitalize}`;
Полезные утилитарные типы
Partial, Required, Readonly, Pick, Omit, Record
Сужение типов
- Используйте
typeof
иinstanceof
для сужения типов:
function padLeft(value: string, padding: string | number) {
if (typeof padding === "number") {
return Array(padding + 1).join(" ") + value;
}
return padding + value;
}
Этот обзор предоставляет основные синтаксис и функции, необходимые для большинства рабочих процессов разработки на TypeScript.