Kurs JavaScript i TypeScript · Moduł 7: Zaawansowany TypeScript
Mapped types (Typy mapowane)
W tej lekcji12
"Nasz park to niezwykle złożony organizm, który stale ewoluuje. Dzisiaj potrzebujemy rejestru wszystkich zagrożeń, jutro będziemy potrzebować listy niezbędnych zapasów, a pojutrze - pełnego spisu dinozaurów wraz z ich statystykami," wyjaśnia John Hammond, założyciel i dyrektor Parku Jurajskiego. "Za każdym razem musimy przetwarzać te same podstawowe dane, ale w różnych konfiguracjach i formatach."
W świecie programowania często stajemy przed podobnym wyzwaniem - przetwarzaniem istniejących typów danych w nowe formy, które lepiej pasują do konkretnych wymagań. TypeScript oferuje eleganckie rozwiązanie tego problemu w postaci typów mapowanych (mapped types), które pozwalają na transformację istniejących typów w sposób systematyczny i typowo bezpieczny.
Czym są typy mapowane?
Typy mapowane w TypeScript pozwalają tworzyć nowe typy na podstawie istniejących poprzez przekształcenie właściwości oryginalnego typu według określonego wzorca. Działa to podobnie do metody map() dla tablic w JavaScript, ale na poziomie typów - zamiast transformować wartości w tablicy, transformujemy właściwości w typie.
Podstawowa składnia typu mapowanego wygląda następująco:
type MappedType<T> = {
[K in keyof T]: TransformedType
}W tym schemacie:
Tto typ źródłowyK in keyof Titeruje przez wszystkie klucze typuTTransformedTypeto nowy typ, który zostanie przypisany do każdej właściwości
Prosty przykład: Readonly
Jednym z najprostszych przykładów typu mapowanego jest Readonly<T>, który tworzy nowy typ, w którym wszystkie właściwości źródłowego typu T są tylko do odczytu:
type Readonly<T> = {
readonly [K in keyof T]: T[K];
};Zastosujmy to do naszego przykładu z Parkiem Jurajskim:
// Definicja typu dla dinozaura
interface Dinosaur {
id: string;
name: string;
species: string;
age: number;
weight: number;
diet: "carnivore" | "herbivore" | "omnivore";
enclosure: string;
}
// Tworzenie niemodyfikowalnego typu dinozaura
type ReadonlyDinosaur = Readonly<Dinosaur>;
// Użycie
const trex: ReadonlyDinosaur = {
id: "TREX-01",
name: "Rexy",
species: "Tyrannosaurus Rex",
age: 7,
weight: 7500,
diet: "carnivore",
enclosure: "Paddock 9"
};
// To nie skompiluje się - właściwości są tylko do odczytu
// trex.name = "Rex"; // Error: Cannot assign to 'name' because it is a read-only propertyZmiana modyfikatorów właściwości
Typy mapowane pozwalają nie tylko na transformację typów właściwości, ale także na dodawanie, usuwanie lub modyfikowanie modyfikatorów, takich jak readonly czy ? (opcjonalność).
Dodawanie modyfikatorów
// Tworzy typ, gdzie wszystkie właściwości są opcjonalne
type Partial<T> = {
[K in keyof T]?: T[K];
};
// Użycie
type PartialDinosaur = Partial<Dinosaur>;
// Obiekt może zawierać tylko część właściwości
const newDino: PartialDinosaur = {
species: "Velociraptor",
diet: "carnivore"
};Usuwanie modyfikatorów
Możemy również usunąć modyfikatory, używając znaku -:
// Tworzy typ, gdzie wszystkie właściwości są wymagane
type Required<T> = {
[K in keyof T]-?: T[K];
};
// Załóżmy, że mamy typ z opcjonalnymi właściwościami
interface OptionalDinosaur {
id: string;
name: string;
species: string;
age?: number;
weight?: number;
diet?: "carnivore" | "herbivore" | "omnivore";
enclosure?: string;
}
// Tworzymy typ, gdzie wszystkie właściwości są wymagane
type RequiredDinosaur = Required<OptionalDinosaur>;
// To nie skompiluje się - brakuje wymaganych właściwości
// const incompleteDino: RequiredDinosaur = {
// id: "VEL-02",
// name: "Blue",
// species: "Velociraptor"
// };Transformacja typów właściwości
Oprócz modyfikowania modyfikatorów właściwości, możemy również transformować typy samych właściwości:
// Transformuje wszystkie właściwości na stringi
type StringifiedDinosaur = {
[K in keyof Dinosaur]: string;
};
const strDino: StringifiedDinosaur = {
id: "TREX-01",
name: "Rexy",
species: "Tyrannosaurus Rex",
age: "7", // Musi być string, nie number
weight: "7500", // Musi być string, nie number
diet: "carnivore",
enclosure: "Paddock 9"
};Warunkowe typy mapowane
Możemy łączyć typy mapowane z typami warunkowymi, aby selektywnie transformować właściwości w zależności od ich typu:
// Transformuje tylko numeryczne właściwości na stringi
type StringifyNumericProps<T> = {
[K in keyof T]: T[K] extends number ? string : T[K];
};
// Użycie
type DinosaurWithStringifiedNumbers = StringifyNumericProps<Dinosaur>;
const mixedDino: DinosaurWithStringifiedNumbers = {
id: "TREX-01",
name: "Rexy",
species: "Tyrannosaurus Rex",
age: "7", // Musi być string (oryginalnie number)
weight: "7500", // Musi być string (oryginalnie number)
diet: "carnivore", // Wciąż unia literałów
enclosure: "Paddock 9"
};Praktyczne zastosowania typów mapowanych
Tworzenie typu konfiguracji na podstawie istniejącego typu
// Definicja typów dla parametrów dinozaura
interface DinosaurParameters {
maxSpeed: number; // km/h
length: number; // metry
height: number; // metry
intelligence: number; // skala 1-10
aggressionLevel: number; // skala 1-10
socialBehavior: "solitary" | "pair" | "pack";
}
// Tworzymy typ konfiguracji, gdzie wszystkie parametry są modyfikowalne
type DinosaurParametersConfig = {
[K in keyof DinosaurParameters]: {
min: number;
max: number;
default: DinosaurParameters[K];
description: string;
};
};
// Użycie
const velociraptorConfig: DinosaurParametersConfig = {
maxSpeed: {
min: 30,
max: 70,
default: 50,
description: "Maksymalna prędkość biegu w km/h"
},
length: {
min: 1.5,
max: 2.5,
default: 2.0,
description: "Długość ciała w metrach"
},
height: {
min: 0.5,
max: 1.0,
default: 0.8,
description: "Wysokość w metrach"
},
intelligence: {
min: 1,
max: 10,
default: 9,
description: "Poziom inteligencji w skali 1-10"
},
aggressionLevel: {
min: 1,
max: 10,
default: 8,
description: "Poziom agresji w skali 1-10"
},
socialBehavior: {
min: 0,
max: 2,
default: "pack",
description: "Zachowania społeczne: samotnik, para lub stado"
}
};Tworzenie formularzy na podstawie modelu danych
// Definicja modelu danych
interface DinosaurRecord {
id: string;
name: string;
species: string;
age: number;
diet: "carnivore" | "herbivore" | "omnivore";
healthStatus: "healthy" | "sick" | "critical";
lastCheckup: Date;
}
// Typ formularza z walidacją
type DinosaurFormValidation = {
[K in keyof DinosaurRecord]: {
required: boolean;
validator?: (value: DinosaurRecord[K]) => boolean;
errorMessage?: string;
};
};
// Implementacja
const dinoFormValidation: DinosaurFormValidation = {
id: {
required: true,
validator: (id) => /^DINO-\d{3}$/.test(id),
errorMessage: "ID musi być w formacie DINO-XXX, gdzie X to cyfra"
},
name: {
required: true,
validator: (name) => name.length >= 2 && name.length <= 50,
errorMessage: "Imię musi mieć od 2 do 50 znaków"
},
species: {
required: true
},
age: {
required: true,
validator: (age) => age > 0 && age < 30,
errorMessage: "Wiek musi być między 0 a 30 lat"
},
diet: {
required: true
},
healthStatus: {
required: true
},
lastCheckup: {
required: true,
validator: (date) => date <= new Date(),
errorMessage: "Data ostatniego badania nie może być w przyszłości"
}
};Śledzenie zmian w obiektach
// Typ identyfikujący, które pola zostały zmienione
type Changed<T> = {
[K in keyof T]: boolean;
};
// Funkcja śledząca zmiany w obiekcie
function trackChanges<T>(original: T, updated: T): Changed<T> {
const result = {} as Changed<T>;
for (const key in original) {
result[key] = original[key] !== updated[key];
}
return result;
}
// Przykład użycia
const originalDino: Dinosaur = {
id: "TREX-01",
name: "Rexy",
species: "Tyrannosaurus Rex",
age: 7,
weight: 7500,
diet: "carnivore",
enclosure: "Paddock 9"
};
const updatedDino: Dinosaur = {
id: "TREX-01",
name: "Rexy",
species: "Tyrannosaurus Rex",
age: 8, // Zmieniono
weight: 8000, // Zmieniono
diet: "carnivore",
enclosure: "Paddock 10" // Zmieniono
};
const changes = trackChanges(originalDino, updatedDino);
console.log(changes);
// Wynik: { id: false, name: false, species: false, age: true, weight: true, diet: false, enclosure: true }Zaawansowane techniki typów mapowanych
Filtrowanie kluczy na podstawie typów wartości
Możemy użyć typów mapowanych razem z typami warunkowymi, aby filtrować klucze obiektu na podstawie typów ich wartości:
// Wybiera klucze, których wartości są określonego typu
type FilterKeys<T, U> = {
[K in keyof T]: T[K] extends U ? K : never;
}[keyof T];
// Wybiera podzbiór obiektu na podstawie typu wartości
type SubType<T, U> = {
[K in FilterKeys<T, U>]: T[K];
};
// Przykładowe użycie: wybieranie tylko numerycznych właściwości
type NumericDinosaurProps = SubType<Dinosaur, number>;
// Wynik: { age: number; weight: number; }
// Użycie
const dinoStats: NumericDinosaurProps = {
age: 7,
weight: 7500
};Rekursywne typy mapowane
Możemy również tworzyć rekursywne typy mapowane, które transformują zagnieżdżone struktury:
// Rekursywnie tworzy tylko do odczytu
type DeepReadonly<T> = {
readonly [K in keyof T]: T[K] extends object ? DeepReadonly<T[K]> : T[K];
};
// Zagnieżdżona struktura danych
interface ParkSystem {
name: string;
status: "online" | "offline" | "maintenance";
subsystems: {
security: {
cameras: number;
fences: {
powered: boolean;
voltage: number;
}[];
};
power: {
mainGenerator: {
output: number;
fuel: number;
};
backupGenerator: {
output: number;
fuel: number;
};
};
};
}
// Tworzenie głęboko niemutowalnej wersji
type ReadonlyParkSystem = DeepReadonly<ParkSystem>;
const parkSystem: ReadonlyParkSystem = {
name: "Jurassic Park Control System",
status: "online",
subsystems: {
security: {
cameras: 48,
fences: [
{ powered: true, voltage: 10000 },
{ powered: true, voltage: 10000 }
]
},
power: {
mainGenerator: {
output: 8000,
fuel: 75
},
backupGenerator: {
output: 3000,
fuel: 100
}
}
}
};
// Nie można modyfikować żadnej właściwości, nawet zagnieżdżonej
// parkSystem.status = "offline"; // Error
// parkSystem.subsystems.security.cameras = 50; // Error
// parkSystem.subsystems.security.fences[0].powered = false; // ErrorZaawansowany przykład: System zarządzania zasobami parku
Poniżej znajduje się zaawansowany przykład wykorzystujący typy mapowane do stworzenia elastycznego systemu zarządzania zasobami Parku Jurajskiego:
// --- Definicje typów bazowych ---
// Bazowy interfejs dla wszystkich zasobów parku
interface ParkResource {
id: string;
name: string;
location: string;
status: "operational" | "maintenance" | "offline";
lastUpdated: Date;
}
// Różne typy zasobów
interface Dinosaur extends ParkResource {
type: "dinosaur";
species: string;
diet: "carnivore" | "herbivore" | "omnivore";
dangerLevel: 1 | 2 | 3 | 4 | 5;
}
interface Vehicle extends ParkResource {
type: "vehicle";
model: string;
capacity: number;
fuelLevel: number;
}
interface Facility extends ParkResource {
type: "facility";
purpose: "visitor" | "research" | "maintenance" | "security";
size: number; // w m²
capacity: number;
}
interface Employee extends ParkResource {
type: "employee";
role: string;
department: "management" | "scientific" | "technical" | "security" | "visitor";
clearanceLevel: 1 | 2 | 3 | 4 | 5;
}
// Unia wszystkich typów zasobów
type Resource = Dinosaur | Vehicle | Facility | Employee;
// --- Typy mapowane dla zarządzania zasobami ---
// Typ do przechowywania referencji do zasobów
type ResourceReferences = {
[K in Resource["type"]]: string[]; // Tablica ID dla każdego typu
};
// Typ do rejestracji procesów zarządzania dla każdego typu zasobu
type ResourceManagementProcesses = {
[K in Resource["type"]]: {
create: (data: Omit<Extract<Resource, { type: K }>, "id" | "lastUpdated">) => string;
update: (id: string, data: Partial<Extract<Resource, { type: K }>>) => boolean;
delete: (id: string) => boolean;
audit: (id: string) => AuditReport<Extract<Resource, { type: K }>>;
};
};
// Typ dla raportów audytowych
type AuditReport<T extends ParkResource> = {
resource: T;
issues: string[];
recommendations: string[];
complianceScore: number;
auditDate: Date;
};
// Typ dla uprawnień dostępu do zasobów
type ResourceAccessPermissions = {
[K in Resource["type"]]: {
read: string[]; // Role, które mogą czytać
write: string[]; // Role, które mogą modyfikować
delete: string[]; // Role, które mogą usuwać
};
};
// Typ dla stanów alertów dla zasobów
type ResourceAlertStatuses = {
[K in Resource["type"]]?: {
[ID: string]: {
level: "info" | "warning" | "critical";
message: string;
timestamp: Date;
acknowledged: boolean;
}[];
};
};
// Typ dla statystyk zasobów
type ResourceStatistics = {
[K in Resource["type"]]: {
total: number;
operational: number;
maintenance: number;
offline: number;
utilizationRate: number; // %
};
};
// Typ dla metadanych formularzy
type ResourceFormMetadata = {
[K in Resource["type"]]: {
[Field in keyof Extract<Resource, { type: K }>]: {
label: string;
required: boolean;
type: "text" | "number" | "select" | "date" | "checkbox";
options?: string[]; // Dla pól select
validation?: RegExp; // Dla walidacji tekstowej
min?: number; // Dla pól liczbowych
max?: number; // Dla pól liczbowych
helpText?: string; // Tekst pomocniczy
};
};
};
// --- Implementacja przykładowa ---
// Przykładowa implementacja metadanych formularzy
const formMetadata: ResourceFormMetadata = {
dinosaur: {
id: { label: "ID", required: true, type: "text", validation: /^DINO-\d{3}$/, helpText: "Format: DINO-XXX" },
name: { label: "Nazwa", required: true, type: "text" },
type: { label: "Typ", required: true, type: "text" },
location: { label: "Lokalizacja", required: true, type: "text" },
status: {
label: "Status",
required: true,
type: "select",
options: ["operational", "maintenance", "offline"]
},
lastUpdated: { label: "Ostatnia aktualizacja", required: true, type: "date" },
species: { label: "Gatunek", required: true, type: "text" },
diet: {
label: "Dieta",
required: true,
type: "select",
options: ["carnivore", "herbivore", "omnivore"]
},
dangerLevel: {
label: "Poziom zagrożenia",
required: true,
type: "select",
options: ["1", "2", "3", "4", "5"],
helpText: "1 - Łagodny, 5 - Ekstremalnie niebezpieczny"
}
},
vehicle: {
id: { label: "ID", required: true, type: "text", validation: /^VEH-\d{3}$/, helpText: "Format: VEH-XXX" },
name: { label: "Nazwa", required: true, type: "text" },
type: { label: "Typ", required: true, type: "text" },
location: { label: "Lokalizacja", required: true, type: "text" },
status: {
label: "Status",
required: true,
type: "select",
options: ["operational", "maintenance", "offline"]
},
lastUpdated: { label: "Ostatnia aktualizacja", required: true, type: "date" },
model: { label: "Model", required: true, type: "text" },
capacity: { label: "Pojemność", required: true, type: "number", min: 1, max: 20 },
fuelLevel: { label: "Poziom paliwa", required: true, type: "number", min: 0, max: 100, helpText: "W procentach" }
},
facility: {
id: { label: "ID", required: true, type: "text", validation: /^FAC-\d{3}$/, helpText: "Format: FAC-XXX" },
name: { label: "Nazwa", required: true, type: "text" },
type: { label: "Typ", required: true, type: "text" },
location: { label: "Lokalizacja", required: true, type: "text" },
status: {
label: "Status",
required: true,
type: "select",
options: ["operational", "maintenance", "offline"]
},
lastUpdated: { label: "Ostatnia aktualizacja", required: true, type: "date" },
purpose: {
label: "Przeznaczenie",
required: true,
type: "select",
options: ["visitor", "research", "maintenance", "security"]
},
size: { label: "Rozmiar", required: true, type: "number", min: 10, helpText: "W metrach kwadratowych" },
capacity: { label: "Pojemność", required: true, type: "number", min: 1 }
},
employee: {
id: { label: "ID", required: true, type: "text", validation: /^EMP-\d{3}$/, helpText: "Format: EMP-XXX" },
name: { label: "Imię i nazwisko", required: true, type: "text" },
type: { label: "Typ", required: true, type: "text" },
location: { label: "Stanowisko pracy", required: true, type: "text" },
status: {
label: "Status",
required: true,
type: "select",
options: ["operational", "maintenance", "offline"]
},
lastUpdated: { label: "Ostatnia aktualizacja danych", required: true, type: "date" },
role: { label: "Stanowisko", required: true, type: "text" },
department: {
label: "Dział",
required: true,
type: "select",
options: ["management", "scientific", "technical", "security", "visitor"]
},
clearanceLevel: {
label: "Poziom dostępu",
required: true,
type: "select",
options: ["1", "2", "3", "4", "5"],
helpText: "1 - Podstawowy, 5 - Pełny dostęp"
}
}
};
// Przykładowe uprawnienia dostępu
const accessPermissions: ResourceAccessPermissions = {
dinosaur: {
read: ["management", "scientific", "technical", "security", "visitor"],
write: ["management", "scientific"],
delete: ["management"]
},
vehicle: {
read: ["management", "technical", "security"],
write: ["management", "technical"],
delete: ["management"]
},
facility: {
read: ["management", "technical", "security"],
write: ["management", "technical"],
delete: ["management"]
},
employee: {
read: ["management"],
write: ["management"],
delete: ["management"]
}
};
// Przykładowe statystyki
const resourceStats: ResourceStatistics = {
dinosaur: {
total: 15,
operational: 12,
maintenance: 2,
offline: 1,
utilizationRate: 80
},
vehicle: {
total: 25,
operational: 20,
maintenance: 3,
offline: 2,
utilizationRate: 75
},
facility: {
total: 12,
operational: 10,
maintenance: 1,
offline: 1,
utilizationRate: 85
},
employee: {
total: 120,
operational: 115,
maintenance: 0,
offline: 5,
utilizationRate: 90
}
};
// Przykładowe alerty
const alertStatuses: ResourceAlertStatuses = {
dinosaur: {
"DINO-001": [
{
level: "warning",
message: "Podwyższony poziom agresji w ciągu ostatnich 24 godzin",
timestamp: new Date(),
acknowledged: false
}
],
"DINO-005": [
{
level: "critical",
message: "Dinozaur poza wyznaczoną zagrodą!",
timestamp: new Date(),
acknowledged: true
}
]
},
facility: {
"FAC-003": [
{
level: "warning",
message: "Wykryto awarię systemu chłodzenia",
timestamp: new Date(),
acknowledged: false
}
]
}
};
// Generator raportów wykorzystujący typy mapowane
function generateResourceReport<T extends Resource["type"]>(
resourceType: T,
detailed: boolean = false
): {
type: T;
stats: ResourceStatistics[T];
alerts: ResourceAlertStatuses[T] | undefined;
resources?: Extract<Resource, { type: T }>[];
} {
// W rzeczywistej implementacji, dane byłyby pobierane z bazy danych
return {
type: resourceType,
stats: resourceStats[resourceType],
alerts: alertStatuses[resourceType],
// Dodajemy listę zasobów tylko jeśli detailed jest true
...(detailed ? { resources: [] as any } : {})
};
}
// Przykładowe użycie
const dinosaurReport = generateResourceReport("dinosaur", true);
console.log(`Raport dla dinozaurów:
- Łączna liczba: ${dinosaurReport.stats.total}
- Operacyjne: ${dinosaurReport.stats.operational}
- W trakcie konserwacji: ${dinosaurReport.stats.maintenance}
- Offline: ${dinosaurReport.stats.offline}
- Współczynnik wykorzystania: ${dinosaurReport.stats.utilizationRate}%
`);
// Wyświetlenie alertów
if (dinosaurReport.alerts) {
console.log("Aktywne alerty:");
Object.entries(dinosaurReport.alerts).forEach(([dinoId, alerts]) => {
alerts.forEach(alert => {
console.log(`- [${alert.level.toUpperCase()}] ${dinoId}: ${alert.message}`);
});
});
}Wbudowane typy mapowane w TypeScript
TypeScript posiada kilka wbudowanych typów mapowanych, które są bardzo przydatne w codziennej pracy:
Partial<T>- Tworzy typ, w którym wszystkie właściwościTsą opcjonalnetype Partial<T> = { [P in keyof T]?: T[P]; };Required<T>- Tworzy typ, w którym wszystkie właściwościTsą wymaganetype Required<T> = { [P in keyof T]-?: T[P]; };Readonly<T>- Tworzy typ, w którym wszystkie właściwościTsą tylko do odczytutype Readonly<T> = { readonly [P in keyof T]: T[P]; };Record<K, T>- Tworzy typ z kluczamiKi wartościami typuTtype Record<K extends keyof any, T> = { [P in K]: T; };Pick<T, K>- Wybiera podzbiór właściwościKz typuTtype Pick<T, K extends keyof T> = { [P in K]: T[P]; };Omit<T, K>- Tworzy typ z wszystkimi właściwościamiToprócz tych wymienionych wKtype Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;Extract<T, U>- Wyciąga zTte typy, które można przypisać doUtype Extract<T, U> = T extends U ? T : never;Exclude<T, U>- Wyklucza zTte typy, które można przypisać doUtype Exclude<T, U> = T extends U ? never : T;NonNullable<T>- WykluczanulliundefinedzTtype NonNullable<T> = T extends null | undefined ? never : T;Parameters<T>- Wyciąga typy parametrów z typu funkcjitype Parameters<T extends (...args: any) => any> = T extends (...args: infer P) => any ? P : never;ReturnType<T>- Wyciąga typ zwracany z typu funkcjitype ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;
Te wbudowane typy mapowane są niezwykle przydatne i pozwalają na bardziej zwięzłe i eleganckie rozwiązania wielu problemów.
Kiedy używać typów mapowanych?
Typy mapowane są szczególnie przydatne w następujących scenariuszach:
Transformacja istniejących typów - gdy potrzebujesz stworzyć wariant istniejącego typu (np.
Readonly<T>,Partial<T>)Budowanie formularzy i walidacji - gdy tworzysz dynamiczne formularze na podstawie modelu danych
Konfiguracje i metadane - gdy potrzebujesz stworzyć strukturę konfiguracji lub metadanych dla każdej właściwości typu
Obsługa API - gdy potrzebujesz transformować typy do formatu wymaganego przez API
Generowanie typów pomocniczych - gdy tworzysz typy narzędziowe, które działają na innych typach
Template literal types
TypeScript oferuje jeszcze jeden zaawansowany mechanizm typów - template literal types. Pozwalają one tworzyć nowe typy stringowe poprzez interpolację, podobnie jak template literals w JavaScript, ale na poziomie typów.
// Podstawowe template literal types
type DinoEvent = `on${string}`;
// Tylko stringi zaczynające się od "on" są akceptowane
const event1: DinoEvent = "onClick"; // OK
const event2: DinoEvent = "onEscape"; // OK
// const event3: DinoEvent = "escape"; // Błąd!
// Łączenie z union types
type Species = "TRex" | "Raptor" | "Triceratops";
type DinoAction = "feed" | "track" | "relocate";
// Generuje: "feedTRex" | "feedRaptor" | ... (wszystkie kombinacje)
type DinoCommand = `${DinoAction}${Species}`;Template literal types są szczególnie przydatne do tworzenia precyzyjnych typów dla nazw zdarzeń, kluczy konfiguracji czy ścieżek API. Działają one na zasadzie interpolacji stringów, ale na poziomie systemu typów - kompilator TypeScript generuje wszystkie możliwe kombinacje.
Podsumowanie
Typy mapowane są potężnym mechanizmem TypeScript, który pozwala na systematyczną transformację typów. Podobnie jak w Parku Jurajskim, gdzie te same dane o dinozaurach mogą być przetwarzane na różne sposoby w zależności od potrzeb, typy mapowane pozwalają nam tworzyć nowe typy na podstawie istniejących, dostosowując je do konkretnych wymagań.
Dzięki typom mapowanym możemy tworzyć bardziej elastyczne, typowo bezpieczne API, formularze, walidacje i wiele innych struktur danych. Mechanizm ten jest szczególnie potężny w połączeniu z innymi zaawansowanymi funkcjami TypeScript, takimi jak typy warunkowe czy inferencja typów.
W miarę jak będziesz zdobywać więcej doświadczenia w TypeScript, typy mapowane staną się nieodzownym narzędziem w twoim arsenale, pozwalającym na tworzenie bardziej ekspresyjnych, bezpiecznych i eleganckich rozwiązań.
Kod do tej lekcji: index.ts
// Typy mapowane (Mapped Types) - Park Jurajski
console.log("=== TYPY MAPOWANE ===\n");
// ===========================================
// 1. Wbudowane typy mapowane
// ===========================================
interface DinosaurConfig {
name: string;
species: string;
weight: number;
height: number;
dangerLevel: number;
isContained: boolean;
}
// Readonly<T> - wszystkie pola tylko do odczytu
type FrozenDino = Readonly<DinosaurConfig>;
// Partial<T> - wszystkie pola opcjonalne
type DinoUpdate = Partial<DinosaurConfig>;
// Pick<T, K> - wybranie podzbioru pol
type DinoSummary = Pick<DinosaurConfig, "name" | "species" | "dangerLevel">;
// Omit<T, K> - pominiecie pol
type DinoPublic = Omit<DinosaurConfig, "isContained" | "dangerLevel">;
// Record<K, T> - mapowanie kluczy na typ
type DinoRegistry = Record<string, DinosaurConfig>;
// ===========================================
// 2. Wlasne typy mapowane
// ===========================================
// Wszystkie pola jako nullable
type Nullable<T> = {
[K in keyof T]: T[K] | null;
};
// Wszystkie pola jako opcjonalne i nullable
type OptionalNullable<T> = {
[K in keyof T]?: T[K] | null;
};
// Pola numeryczne zamienione na string (formatowanie)
type Stringify<T> = {
[K in keyof T]: T[K] extends number ? string : T[K];
};
// Tylko pola o typie numerycznym
type NumericFields<T> = {
[K in keyof T as T[K] extends number ? K : never]: T[K];
};
// Dodanie prefixu 'get' do nazw pol
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
// ===========================================
// 3. Praktyczne zastosowania
// ===========================================
// Formularz z walidacja - kazde pole ma blad
type FormErrors<T> = {
[K in keyof T]?: string;
};
// Stan ladowania dla kazdego pola
type LoadingState<T> = {
[K in keyof T]: {
value: T[K];
isLoading: boolean;
error?: string;
};
};
// ===========================================
// Test
// ===========================================
// Readonly
console.log("--- Readonly ---");
const frozen: FrozenDino = {
name: "Rexy",
species: "T-Rex",
weight: 8000,
height: 5.5,
dangerLevel: 10,
isContained: true
};
console.log("Frozen:", frozen.name);
// frozen.name = "New"; // Error! - readonly
// Partial - aktualizacja czesciowa
console.log("\n--- Partial ---");
function updateDino(current: DinosaurConfig, updates: DinoUpdate): DinosaurConfig {
return { ...current, ...updates };
}
const updated = updateDino(frozen as DinosaurConfig, { weight: 8200, height: 5.6 });
console.log("Po aktualizacji:", updated.weight, "kg,", updated.height, "m");
// Pick
console.log("\n--- Pick ---");
const summary: DinoSummary = { name: "Rexy", species: "T-Rex", dangerLevel: 10 };
console.log("Podsumowanie:", JSON.stringify(summary));
// Record
console.log("\n--- Record ---");
const registry: DinoRegistry = {
"DINO-001": { name: "Rexy", species: "T-Rex", weight: 8000, height: 5.5, dangerLevel: 10, isContained: true },
"DINO-002": { name: "Blue", species: "Velociraptor", weight: 15, height: 1.8, dangerLevel: 8, isContained: true },
};
Object.entries(registry).forEach(([id, dino]) => {
console.log(`${id}: ${dino.name} (${dino.species})`);
});
// Nullable
console.log("\n--- Nullable (wlasny) ---");
const maybeDino: Nullable<DinoSummary> = {
name: "Nieznany",
species: null,
dangerLevel: null
};
console.log("Czesciowe dane:", JSON.stringify(maybeDino));
// Stringify
console.log("\n--- Stringify (wlasny) ---");
const formatted: Stringify<DinoSummary> = {
name: "Rexy",
species: "T-Rex",
dangerLevel: "10/10" // number -> string
};
console.log("Sformatowany:", JSON.stringify(formatted));
// FormErrors
console.log("\n--- FormErrors ---");
type DinoForm = Pick<DinosaurConfig, "name" | "weight" | "species">;
const errors: FormErrors<DinoForm> = {
name: "Nazwa jest wymagana",
weight: "Waga musi byc dodatnia"
};
Object.entries(errors).forEach(([field, error]) => {
console.log(` ${field}: ${error}`);
});
console.log("\nTypy mapowane = transformacja typow jak danych!");Hasła z dokumentacji w tej lekcji
Widzisz błąd w tej lekcji?
Sprawdź się
Odpowiedz na pytania z tej lekcji. Wybierz odpowiedź, a od razu zobaczysz, czy jest poprawna.
1. Co to są template literal types w TypeScript?
Zadania praktyczne w grze
- Edytor kodu
Stwórz custom mapped types dla systemu uprawnień parku
- Klikanie w kolejności
Ułóż elementy mapped type Readonly:
- Klikanie w kolejności
Ułóż elementy typu opartego na keyof i typeof:
- Układanie w pionie
Uporządkuj etapy tworzenia generycznego utility type: