Podmienené typy a infer
conditional.ts
export type ArrayElement<T> = T extends readonly (infer Item)[]
? Item
: never;
export type ToArray<T> = T extends unknown ? T[] : never;
export type WholeArray<T> = [T] extends [unknown] ? T[] : never;
export type IsNever<T> = [T] extends [never] ? true : false;
export type ApiResult<T> = T extends PromiseLike<infer Value>
? Value
: T;
Súvisiaci článok (anglicky): TypeScript Generics.
T extends U ? X : Y vyberá vetvu podľa priraditeľnosti typov, nie podľa podmienky JavaScriptu. V pravdivej vetve možno využiť informácie zo vzoru. ArrayElement rozpozná meniteľné aj readonly polia a n-tice pomocou readonly (infer Item)[]; iné typy vracajú never. ApiResult rozbalí jednu vrstvu PromiseLike. Na rekurzívne rozbalenie použite Awaited. Pri preťažených funkciách ReturnType odvodzuje typ z poslednej signatúry, nie výberom podľa argumentov. [1][3]
Distribúcia zjednotení a never
Ak je vľavo od extends samostatný parameter T, každý člen zjednotenia sa spracuje zvlášť. ToArray pre string a number vytvorí zjednotenie homogénnych polí. WholeArray zabalí obe strany do n-tíc a umožní oba typy prvkov v jednom poli. Distribúcia cez never dáva never, pretože neexistujú členy. IsNever preto používa n-tice. any môže narušiť podmienenú inferenciu; pre nedôveryhodné dáta použite unknown. [1]
Mapovanie vlastností a modifikátorov
mapped.ts
import type { IsNever } from "./conditional";
export interface Profile {
readonly id: string;
displayName: string;
bio?: string | null;
active: boolean;
}
export type FieldErrors<T> = {
-readonly [Key in keyof T]?: string;
};
export type EditableProfile = Pick<Profile, "displayName" | "bio">;
export type ProfilePatch = Partial<EditableProfile>;
export type RequiredFields<T> = {
[Key in keyof T]-?: T[Key];
};
export type ChangeHandlers<T> = {
[Key in keyof T as Key extends string
? `on${Capitalize<Key>}Change`
: never]-?: (value: T[Key]) => void;
};
export type StringFields<T> = {
[Key in keyof T as T[Key] extends string ? Key : never]: T[Key];
};
type IsString<T> = [T] extends [string] ? true : false;
type IsNonNullableString<T> = IsNever<NonNullable<T>> extends true
? false
: IsString<NonNullable<T>>;
export type NonNullableStringFields<T> = {
[Key in keyof T as IsNonNullableString<T[Key]> extends true
? Key
: never]: T[Key];
};
Súvisiaci článok (anglicky): TypeScript Utility Types.
Mapovaný typ prechádza keyof T a číta typ hodnoty pomocou T[Key]. Homomorfné mapovanie zachováva modifikátory, ak ich výslovne nezmeníme. FieldErrors odstráni readonly a pridá voliteľnosť. RequiredFields odstráni ?, ale nevytvorí hodnoty. S exactOptionalPropertyTypes sa chýbajúce bio líši od bio: undefined: ProfilePatch povoľuje vynechanie alebo null, nie explicitné undefined. Čítanie voliteľného poľa môže stále vrátiť undefined. [2][4][5]
Premapovanie a filtrovanie kľúčov
as mení kľúč a never ho vylučuje. ChangeHandlers vytvára názvy ako onDisplayNameChange so správnym typom argumentu. Zámerne vynecháva číselné kľúče a symboly; voliteľné pole môže dodať undefined. StringFields zachováva len typy plne priraditeľné k string, teda nie voliteľné bio. NonNullableStringFields porovnáva po odstránení null a undefined a odmieta never. Pôvodný typ hodnoty zostáva. Vyhnite sa kolíziám názvov. [2][6]
Diskriminované zjednotenia a udalosti
unions.ts
export type Payment =
| { id: string; kind: "card"; lastFour: string }
| { id: string; kind: "transfer"; reference: string };
export type DistributiveOmit<T, Key extends PropertyKey> =
T extends unknown ? Omit<T, Key> : never;
export type PublicPayment = DistributiveOmit<Payment, "id">;
export type PaymentHandlers = {
[Event in PublicPayment as Event["kind"]]: (event: Event) => string;
};
export const handlers = {
card: (event) => event.lastFour,
transfer: (event) => event.reference,
} satisfies PaymentHandlers;
export function describePayment(payment: PublicPayment): string {
switch (payment.kind) {
case "card": {
return handlers.card(payment);
}
case "transfer": {
return handlers.transfer(payment);
}
}
}
Omit<Payment, "id"> pracuje so spoločnými kľúčmi a stráca polia jednotlivých variantov. DistributiveOmit vykonáva operáciu pre každý variant zvlášť. PaymentHandlers mapuje objekty podľa kind a priraďuje správny typ argumentu. satisfies odhalí chýbajúce alebo nekompatibilné obsluhy a zachová užitočnú inferenciu. handlers[payment.kind](payment) môže zlyhať pre stratu korelácie. switch zužuje typ bez pretypovania; kind je pre každý variant jedinečný. [1][2][7][8]
Hranica medzi typmi a behom programu
projection.ts
export interface Account {
id: string;
displayName: string;
accessToken: string;
}
export type PublicAccount = Pick<Account, "id" | "displayName">;
export function toPublicAccount(account: Account): PublicAccount {
return {
id: account.id,
displayName: account.displayName,
};
}
Súvisiaci článok (anglicky): TypeScript Type Guards and Type Narrowing.
Pick a Omit nemažú vlastnosti objektu. Štrukturálne typovanie umožňuje priradiť Account k PublicAccount, ale token zostáva a môže sa dostať do JSON. toPublicAccount explicitne vyberá povolené polia. Nedôveryhodný vstup vyžaduje parser alebo validačnú schému za behu; autorizáciu vynucuje backend. readonly pôsobí plytko a nezmrazí objekt. [3][9]
Testovanie typových kontraktov
type-tests.ts
import type {
ApiResult,
ArrayElement,
IsNever,
ToArray,
WholeArray,
} from "./conditional";
import type {
ChangeHandlers,
FieldErrors,
NonNullableStringFields,
Profile,
ProfilePatch,
RequiredFields,
StringFields,
} from "./mapped";
import { handlers } from "./unions";
import type { Payment, PublicPayment } from "./unions";
// A generic-function comparison for these concrete type contracts.
type Equal<A, B> = (<T>() => T extends A ? 1 : 2) extends
(<T>() => T extends B ? 1 : 2)
? true
: false;
type Expect<T extends true> = T;
export type ContractTests = [
Expect<Equal<ArrayElement<readonly [1, 2]>, 1 | 2>>,
Expect<Equal<ArrayElement<string>, never>>,
Expect<Equal<ToArray<string | number>, string[] | number[]>>,
Expect<Equal<WholeArray<string | number>, (string | number)[]>>,
Expect<Equal<IsNever<never>, true>>,
Expect<Equal<IsNever<string>, false>>,
Expect<Equal<keyof StringFields<Profile>, "id" | "displayName">>,
Expect<
Equal<keyof NonNullableStringFields<Profile>, "id" | "displayName" | "bio">
>,
Expect<Equal<ToArray<never>, never>>,
Expect<Equal<ApiResult<Promise<number>>, number>>,
Expect<Equal<ApiResult<Promise<Promise<number>>>, Promise<number>>>,
Expect<Equal<RequiredFields<Profile>["bio"], string | null>>,
Expect<Equal<keyof Omit<Payment, "id">, "kind">>,
Expect<
Equal<Extract<PublicPayment, { kind: "card" }>["lastFour"], string>
>,
Expect<
Equal<
Parameters<ChangeHandlers<Profile>["onBioChange"]>[0],
string | null | undefined
>
>,
];
export const errors: FieldErrors<Profile> = {};
errors.id = "Invalid identifier";
export const patch: ProfilePatch = { bio: null };
// @ts-expect-error: explicit undefined is not allowed in this patch.
export const invalidPatch: ProfilePatch = { bio: undefined };
// @ts-expect-error: id is not an editable field.
export const forbiddenPatch: ProfilePatch = { id: "42" };
// @ts-expect-error: a card variant requires lastFour.
export const invalidPayment: PublicPayment = { kind: "card" };
export function invalidDispatch(payment: PublicPayment): string {
// @ts-expect-error: the indexed call loses variant correlation.
return handlers[payment.kind](payment);
}
runtime.test.cjs
const { test } = require("node:test");
const assert = require("node:assert/strict");
const { toPublicAccount } = require("./dist/projection.js");
const { describePayment } = require("./dist/unions.js");
test("projects only public account fields", () => {
// Given
const account = {
id: "42",
displayName: "Ada",
accessToken: "example-secret",
};
// When
const result = toPublicAccount(account);
// Then
assert.deepEqual(result, { id: "42", displayName: "Ada" });
assert.equal(Object.hasOwn(result, "accessToken"), false);
});
test("describes a card payment", () => {
// Given
const payment = { kind: "card", lastFour: "1234" };
// When
const result = describePayment(payment);
// Then
assert.equal(result, "1234");
});
test("describes a transfer", () => {
// Given
const payment = { kind: "transfer", reference: "ABC" };
// When
const result = describePayment(payment);
// Then
assert.equal(result, "ABC");
});
tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"module": "CommonJS",
"strict": true,
"exactOptionalPropertyTypes": true,
"noUncheckedIndexedAccess": true,
"noEmitOnError": true,
"outDir": "dist"
},
"include": ["*.ts"]
}
Equal a Expect overujú konkrétne typy; @ts-expect-error kontroluje, že zakázané priradenia stále zlyhávajú. Nepoužitá direktíva vyvolá diagnostiku, ale nezaručuje konkrétnu chybu. Izolujte jedinú príčinu zlyhania a skutočné správanie testujte zvlášť. Given-When-Then overuje výber verejných polí v Node.js. type-tests.ts je iba kompilačný test. [10]
Zjednodušenie a meranie nákladov
Súvisiaci článok (anglicky): TypeScript tsconfig.json.
Začnite vstavanými pomocnými typmi a popisnými názvami. Rekurzia nad ľubovoľnými objektmi môže zle spracovať Date, funkcie, polia, n-tice a cykly; určte podporované štruktúry pre DeepReadonly. Karteziánske súčiny šablónových literálových typov a hlboká rekurzia môžu zvýšiť náklady kompilácie. Porovnajte tsc --extendedDiagnostics pred zmenou a po nej v rovnakom projekte s rovnakým kompilátorom. Univerzálna bezpečná hĺbka neexistuje. [6][11]
