Ściąga TypeScript: opanuj podstawowe koncepcje i najlepsze praktyki
Instalacja, uruchamianie, typy, klasy, wszystkie podstawy
Page content
Oto moja skrócona karta cheat TypeScript, obejmująca kluczowe pojęcia, składnię i przykłady kodu często odwoływane się przez programistów:
Karta cheat TypeScript
Rozpoczęcie pracy
- Zainstaluj globalnie:
npm install -g typescript
- Skompiluj plik:
tsc filename.ts
- Sprawdź wersję:
tsc --version
Podstawowe typy
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;
Typy unii i literału
let id: number | string = 42;
let direction: 'left' | 'right' = 'left';
Aliasy typów i interfejsy
type Point = { x: number; y: number };
interface Person { name: string; age: number; }
let user: Person = { name: "Alice", age: 25 };
Funkcje
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); }
Klasy
class Animal {
name: string;
constructor(name: string) { this.name = name; }
move(distance: number = 0): void { console.log(`${this.name} moved ${distance}`); }
}
Modyfikatory dostępu
public
(domyślnie),private
,protected
,readonly
class Point {
constructor(private x: number, private y: number) {}
}
Generiki
function identity(arg: T): T { return arg; }
let output = identity("myString");
Enumy
enum ResourceType { BOOK, FILE, FILM }
let r: ResourceType = ResourceType.BOOK;
Asercje typów / rzutowanie
let someVal: unknown = "Hello";
let strLength: number = (someVal as string).length;
Moduły
// Eksport
export function foo() {}
// Import
import { foo } from "./module";
Zaawansowane typy
- Intersekcja:
type A = { a: number }; type B = { b: number }; type AB = A & B; // { a: number, b: number }
- Warunkowe:
type IsString = T extends string ? true : false;
- Mapowane:
type Readonly = { readonly [P in keyof T]: T[P]; }
- Typ literału szablonowego:
type EventName = `on${Capitalize}`;
Użyteczne typy pomocnicze
Partial, Required, Readonly, Pick, Omit, Record
Narzozowanie typów
- Użyj
typeof
iinstanceof
do węższenia typów:
function padLeft(value: string, padding: string | number) {
if (typeof padding === "number") {
return Array(padding + 1).join(" ") + value;
}
return padding + value;
}
Ten przegląd dostarcza podstawowej składni i funkcji niezbędnych do większości przepływów pracy w TypeScript.