TypeScript 5.5 / 5.6
Inferred Type Predicates, using / await using (Symbol.dispose), Isolated Declarations i verbatimModuleSyntax.
TypeScript 5.x — kluczowe funkcje według wersji
TS 5.0 do 5.6 — const params, satisfies, predicates, using, verbatimModuleSyntax i narzędzia.
| Wersja | Funkcja | Opis |
|---|---|---|
| TS 5.0 | const type parameters, satisfies (4.9) | Literal type preservation, type checking bez narrowing |
| TS 5.4 | NoPropertyAccessFromIndexSignature | Safer index signatures, preserved narrowing in closures |
| TS 5.5 | Inferred Type Predicates, Isolated Declarations | Auto type guards z filter(), parallel type checking |
| TS 5.6 | using / await using (Symbol.dispose) | Explicit Resource Management — auto cleanup |
| TS 5.x | verbatimModuleSyntax | Klarowne import type — bundler safe |
| Narzędzia | ts-reset, type-fest, ts-toolbelt | Utility types, poprawki standardowych typów |
Często zadawane pytania
TypeScript 5.5 — Inferred Type Predicates i co nowego?
TypeScript 5.5 (2024-06): kluczowe features. Inferred Type Predicates: TypeScript automatycznie inferuje type predicate z filtrowania. Wcześniej: function isString(x: any): x is string { return typeof x === 'string' }. TS 5.5: const strings = ['a', 1, 'b', 2].filter(x => typeof x === 'string'). Typ: string[] automatycznie! Bez type assertion. const strOrNum: (string | number)[] = [1, 'a', 2]. const strOnly = strOrNum.filter(x => typeof x === 'string'). strOnly: string[]. Control flow improvements: dokładniejsza analiza. const narrowed: string = condition ? maybeString : ''. TypeScript rozumie narrowing w closure. Isolated Declarations: --isolatedDeclarations. Każdy plik musi mieć explicit types. Nie inferuj z innego pliku. Szybsze parallel type checking. Monorepo benefit: każdy pakiet niezależnie type-check. tsconfig.json: {compilerOptions: {isolatedDeclarations: true}}. Requires explicit: function add(a: number, b: number): number — return type required. export const x: string = 'hello' — type annotation required. JSDoc: explicit dla monorepo. Nowe regex: TypeScript sprawdza regex syntax. Błędy w nieprawidłowych regex. /[a-z]+/ — ok. /[z-a]+/ — błąd kompilacji (invalid range). Config performance: tsconfig references szybsze. Composite projects. Build mode: tsc --build.
TypeScript 5.6 i using declarations (Explicit Resource Management)?
TypeScript 5.6 (2024-09): using declarations. Explicit Resource Management (TC39 Stage 4). using i await using. using: automatyczny cleanup synchroniczny. const file = using openFile('data.txt'). // file.close() wywołane automatycznie po bloku. Musi implementować Symbol.dispose. Implementacja: const disposable = { [Symbol.dispose]() { cleanup() } }. using resource = disposable. await using: asynchroniczny cleanup. await using db = await connectToDb(). // db.close() wywołane po await. Symbol.asyncDispose. DisposableStack: grupuj disposable. const stack = new DisposableStack(). stack.use(resource1). stack.use(resource2). stack.dispose() — dispose all. AsyncDisposableStack: async version. Praktyczne: file handles. database connections. AbortController. Web sockets. React nie używa (useEffect nadal). Node.js 20+: Symbol.dispose wbudowane. fs.FileHandle[Symbol.asyncDispose]. using fh = await fs.promises.open('file.txt', 'r'). Nieoczekiwane użycia: cancelable fetch: const ctl = using new AbortController(). fetch(url, {signal: ctl.signal}). // ctl.abort() po bloku. TS 5.6 inne: `--noUncheckedSideEffectImports`. import 'styles.css' — sprawdza że plik istnieje. Iterator helper methods: .map(), .filter(), .take() dla iteratorów. Lazy evaluation. Szybszy od Array.
TypeScript — verbatimModuleSyntax i Isolated Modules?
verbatimModuleSyntax (TS 5.0+): rekomendowane dla nowoczesnych projektów. Zamienia isolatedModules + importsNotUsedAsValues + preserveValueImports. Reguła: import type MUSI być type-only. import {type User, getUser} — ok. import {User} gdy User to typ — błąd! Dlaczego ważne: bundlery (esbuild, swc) nie sprawdzają typów. Usuwają import {User} gdy User to typ. Ale niektóre importy mają side effects. verbatimModuleSyntax zapobiega dwuznacznościom. tsconfig: {compilerOptions: {verbatimModuleSyntax: true}}. Efekt: import type {User} from './types' — usuwa. import {User} from './types' — zostawia (runtime). Type assertions: as const satisfies. const config = {port: 3000, host: 'localhost'} as const satisfies {port: number, host: string}. Exact type + satisfies. const enum: verbatimModuleSyntax zabrania const enum (nie pure type). Użyj zwykłego enum. Lub as const object. Module detection: {moduleDetection: 'force'} — traktuj jako moduł. Bez export {} na końcu pliku. Strict mode: strictest tsconfig 2024: strict, noUncheckedIndexedAccess, exactOptionalPropertyTypes, noImplicitReturns, noFallthroughCasesInSwitch, forceConsistentCasingInFileNames, verbatimModuleSyntax, isolatedDeclarations (monorepo).
TypeScript 5.x — satisfies, const type parameters i noisy errors?
satisfies (TS 4.9, używaj!): sprawdź typ bez tracenia literalności. const palette = {red: [255, 0, 0], green: '#00ff00'} satisfies Record string, string | number[]. palette.red — [255, 0, 0] (nie string | number[]). palette.green — string (nie string | number[]). Typ preserved. const type parameters (TS 5.0): function makeArray(a: T): T[] { return [a] }. makeArray('hello') — string[] (nie ('hello')[]). Lepsze z const: function makeArray(a: T): T[] z const T. makeArray('hello') — ['hello'] (literal!). Override (TS 4.3): class Base { greet(): string { return 'Hello' } }. class Derived extends Base { override greet() { return 'Hi' } }. Błąd gdy nie istnieje w Base. NoPropertyAccessFromIndexSignature: ts error gdy index signature. Explicit bracket notation. Sprawdzenie. Template literal types (TS 4.1+): type Route = `/${string}`. type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE'. type Endpoint = `${HttpMethod} ${Route}`. const endpoint: Endpoint = 'GET /users'. Declare: declare module '*.svg' { const content: string. export default content }. Ambient declarations. Import.meta: type: {importMeta: 'bundler'} w tsconfig. import.meta.env — Vite. import.meta.url — Node. Satisfies + as const: kombinacja: const config = {theme: 'dark', lang: 'pl'} as const satisfies Config. Najsilniejsza typizacja.
Narzędzia TypeScript 2024 — ts-reset, type-fest, ts-toolbelt?
ts-reset: Matt Pocock. Poprawia standardowe typy TS. npm install @total-typescript/ts-reset. import '@total-typescript/ts-reset'. Co poprawia: Array.isArray(x) — unknown[] zamiast any[]. JSON.parse() — unknown zamiast any. fetch().json() — unknown. Array.filter(Boolean) — usuwa undefined. Element.querySelector — zwraca Element (nie null zawsze). Set.has(value) — type-safe (TS blokowało non-set-type). .includes() — type-safe. type-fest: Sindre Sorhus. Użyteczne utility types. Konditional, Mapping, Template. Async, ReadonlyDeep, Get, ValueOf. npm install type-fest. import type {ReadonlyDeep, Except, Promisable} from 'type-fest'. ReadonlyDeep: rekurencyjnie readonly. Except: jak Omit ale z autocompletion. Promisable: T | Promise T. ts-toolbelt: bardzo zaawansowane. Functional types. Recursion. Union manipulation. zod-to-ts: generuj TypeScript z Zod schema. Dla dokumentacji. json-schema-to-ts: JSON Schema -> TS types. Szybko z API. TypeScript ESLint (typescript-eslint v7): parser + rules. Typed lint rules. await using w lint. performancowe rules. tRPC type inference: end-to-end types bez schema. Automatyczne z server -> client. Matt Pocock Total TypeScript: kurs i narzędzia. Najlepsze źródło TS wiedzy. Twitch livestreams. ts-reset darmowe.
Powiązane artykuły
Skontaktuj się z nami
Porozmawiajmy o Twoim projekcie. Bezpłatna wycena w ciągu 24 godzin.
Wyślij zapytanie
Telefon
+48 790 814 814
Pon-Pt: 9:00 - 18:00
adam@fotz.pl
Odpowiadamy w ciągu 24h
Adres
Plac Wolności 16
61-739 Poznań
Godziny pracy
Wolisz porozmawiać?
Zadzwoń teraz i porozmawiaj z naszym specjalistą o Twoim projekcie.
Zadzwoń teraz