JavaScript and TypeScript course ยท Module 7: Advanced TypeScript
Conditional Types
In this lesson8
"Dr. Wu, we have a situation," says a nervous lab assistant. "The DNA pattern we're trying to sequence could be from either a predatory or herbivorous dinosaur species, but we need different processing protocols depending on which one we're dealing with."
Dr. Henry Wu, Jurassic Park's chief geneticist, responds calmly: "That's not a problem. Our sequencing algorithms are intelligent enough to detect predation markers in DNA and automatically apply the appropriate protocol. That's the flexibility of our system."
Just like the advanced DNA sequencing algorithms in Jurassic Park, TypeScript has a mechanism called conditional types that allows dynamically determining types based on other types. This tool enables creating more flexible and precise APIs that adapt to different scenarios.
Conditional Type Basics
Conditional types in TypeScript work similarly to conditional expressions in JavaScript, but at the type level. Their syntax resembles the ternary operator:
T extends U ? X : YThis should be read as: "If type T extends (is compatible with) type U, then the result is type X, otherwise type Y".
Simple Example
Let's create a simple function that processes an object representing a dinosaur and returns different results depending on its diet:
type Carnivore = { type: "carnivore"; huntingSkill: number };
type Herbivore = { type: "herbivore"; foragingSkill: number };
type Dinosaur = Carnivore | Herbivore;
// Conditional type determining the appropriate result type
type DinosaurActivity<T extends Dinosaur> = T extends Carnivore
? { activity: "hunting"; preyTargeted: string }
: { activity: "grazing"; plantsConsumed: number };
// Function using the conditional type
function trackDinosaurActivity<T extends Dinosaur>(dino: T): DinosaurActivity<T> {
if (dino.type === "carnivore") {
// TypeScript knows that for Carnivore we should return { activity: "hunting"; preyTargeted: string }
return {
activity: "hunting",
preyTargeted: "Gallimimus"
} as DinosaurActivity<T>;
} else {
// TypeScript knows that for Herbivore we should return { activity: "grazing"; plantsConsumed: number }
return {
activity: "grazing",
plantsConsumed: 42
} as DinosaurActivity<T>;
}
}
// Example usage
const trex: Carnivore = { type: "carnivore", huntingSkill: 10 };
const triceratops: Herbivore = { type: "herbivore", foragingSkill: 8 };
const trexActivity = trackDinosaurActivity(trex);
console.log(trexActivity.activity); // "hunting"
console.log(trexActivity.preyTargeted); // "Gallimimus"
const triceratopsActivity = trackDinosaurActivity(triceratops);
console.log(triceratopsActivity.activity); // "grazing"
console.log(triceratopsActivity.plantsConsumed); // 42In this example, the type DinosaurActivity<T> changes depending on whether T extends Carnivore or not. This allows us to return different data structures, and TypeScript provides full type support for both cases.
Distributive Conditional Types
One of the key features of conditional types is their distributive behavior with union types. When we apply a conditional type to a union type, the condition is applied to each element of the union separately.
type ToArray<T> = T extends any ? T[] : never;
// With a simple type, the result is simple
type NumberArray = ToArray<number>; // number[]
// With a union type, the condition is applied distributively
type NumberOrStringArray = ToArray<number | string>; // number[] | string[]In the second case, ToArray<number | string> is equivalent to ToArray<number> | ToArray<string>, which gives number[] | string[], not (number | string)[].
We can apply this to our dinosaur example:
// Defining more dinosaur types
type TRex = { species: "tyrannosaurus"; strength: number };
type Velociraptor = { species: "velociraptor"; speed: number };
type Triceratops = { species: "triceratops"; armorLevel: number };
type Brachiosaurus = { species: "brachiosaurus"; height: number };
// Conditional type filtering predators
type IsPredator<T> = T extends { species: "tyrannosaurus" | "velociraptor" } ? T : never;
// Distributive application on union types
type Predators = IsPredator<TRex | Velociraptor | Triceratops | Brachiosaurus>;
// Result: TRex | Velociraptor
// We can also filter herbivores
type IsHerbivore<T> = T extends { species: "triceratops" | "brachiosaurus" } ? T : never;
type Herbivores = IsHerbivore<TRex | Velociraptor | Triceratops | Brachiosaurus>;
// Result: Triceratops | BrachiosaurusInferred Types
TypeScript allows extracting (inferring) types from other types using the infer keyword. This is particularly useful in conditional types.
// Type that extracts the return type of a function
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
// Example usage
function studyDinosaur(specimen: string): { species: string; age: number } {
return {
species: "Velociraptor",
age: 5
};
}
// Extracted return type of the studyDinosaur function
type StudyResult = ReturnType<typeof studyDinosaur>; // { species: string; age: number }In this example, infer R tells TypeScript to "deduce" the return type of the function and assign it to type R, which is then used as the result of the conditional type.
We can create more complex type extraction examples, for instance:
// Type representing dinosaur DNA
type DinosaurDNA = {
species: string;
genomeSequence: string;
markers: {
predatory?: boolean;
aquatic?: boolean;
flying?: boolean;
size: "small" | "medium" | "large";
};
};
// Extracting markers from DNA
type ExtractMarkers<T> = T extends { markers: infer M } ? M : never;
// Extracting size from markers
type ExtractSize<T> = T extends { size: infer S } ? S : never;
// Example usage
type DinosaurMarkers = ExtractMarkers<DinosaurDNA>;
// { predatory?: boolean; aquatic?: boolean; flying?: boolean; size: "small" | "medium" | "large"; }
type DinosaurSize = ExtractSize<DinosaurMarkers>;
// "small" | "medium" | "large"Practical Applications of Conditional Types
Conditional types are especially useful in advanced programming scenarios, such as:
1. Creating Flexible API Components
// Example API for dinosaur operations
interface DinosaurOperations<T> {
create: (data: T) => Promise<T>;
update: (id: string, data: Partial<T>) => Promise<T>;
delete: (id: string) => Promise<void>;
// Method that returns different types depending on parameter T
analyze: T extends { genomeSequence: string }
? (id: string) => Promise<{ compatibilityScore: number }>
: (id: string) => Promise<{ behaviorPrediction: string }>;
}
// Implementation for dinosaurs with genome sequence
interface GenomeSequencedDino {
id: string;
name: string;
genomeSequence: string;
}
// Implementation for dinosaurs without genome sequence
interface BehaviorStudiedDino {
id: string;
name: string;
observedBehaviors: string[];
}
// Different implementations for different types
function createDinosaurAPI<T extends GenomeSequencedDino | BehaviorStudiedDino>(
baseUrl: string
): DinosaurOperations<T> {
return {
create: (data: T) => fetch(`${baseUrl}/create`, {
method: 'POST',
body: JSON.stringify(data)
}).then(res => res.json()),
update: (id: string, data: Partial<T>) => fetch(`${baseUrl}/${id}`, {
method: 'PUT',
body: JSON.stringify(data)
}).then(res => res.json()),
delete: (id: string) => fetch(`${baseUrl}/${id}`, {
method: 'DELETE'
}).then(() => undefined),
// The analyze method implementation will differ depending on type T
analyze: ((id: string) => {
if ('genomeSequence' in { ...({} as T) }) {
return fetch(`${baseUrl}/${id}/genome-analysis`)
.then(res => res.json());
} else {
return fetch(`${baseUrl}/${id}/behavior-analysis`)
.then(res => res.json());
}
}) as any // Cast needed due to TypeScript runtime limitations
};
}
// Using different APIs
const genomeAPI = createDinosaurAPI<GenomeSequencedDino>('/api/genome-dinos');
const result1 = await genomeAPI.analyze('dino-1'); // { compatibilityScore: number }
const behaviorAPI = createDinosaurAPI<BehaviorStudiedDino>('/api/behavior-dinos');
const result2 = await behaviorAPI.analyze('dino-2'); // { behaviorPrediction: string }2. Implementing Type Patterns
// Helper type Exclude - excludes types from a union
type Exclude<T, U> = T extends U ? never : T;
// Example: excluding dangerous dinosaurs
type DangerousDinosaurs = "Tyrannosaurus" | "Velociraptor" | "Spinosaurus";
type AllDinosaurs = "Tyrannosaurus" | "Triceratops" | "Velociraptor" | "Brachiosaurus" | "Stegosaurus" | "Spinosaurus";
type SafeDinosaurs = Exclude<AllDinosaurs, DangerousDinosaurs>;
// "Triceratops" | "Brachiosaurus" | "Stegosaurus"
// Helper type Extract - extracts types meeting a condition
type Extract<T, U> = T extends U ? T : never;
// Example: extracting dinosaurs from the Jurassic era
type JurassicDinosaurs = "Stegosaurus" | "Brachiosaurus" | "Allosaurus";
type CretaceousDinosaurs = "Tyrannosaurus" | "Triceratops" | "Velociraptor";
type AllEras = JurassicDinosaurs | CretaceousDinosaurs;
type OnlyJurassic = Extract<AllEras, JurassicDinosaurs>;
// "Stegosaurus" | "Brachiosaurus" | "Allosaurus"
// Helper type NonNullable - removes null and undefined from a type
type NonNullable<T> = T extends null | undefined ? never : T;
// Example: ensuring we have non-empty dinosaur data
type PossibleDinoData = { name: string; weight: number } | null | undefined;
type DefiniteDinoData = NonNullable<PossibleDinoData>;
// { name: string; weight: number }3. Creating Type Mappers
// Type Mapper transforming object properties from one type to another
type MapProperties<T, U> = {
[K in keyof T]: T[K] extends object ? MapProperties<T[K], U> : U;
};
// Example: mapping numeric values to strings
type DinosaurStats = {
name: string;
physicalTraits: {
height: number;
weight: number;
speed: number;
};
behavioralTraits: {
aggression: number;
intelligence: number;
packBehavior: number;
};
};
// Transforming all numbers to strings for display purposes
type DinosaurStatsForDisplay = MapProperties<DinosaurStats, string>;
/*
{
name: string;
physicalTraits: {
height: string;
weight: string;
speed: string;
};
behavioralTraits: {
aggression: string;
intelligence: string;
packBehavior: string;
};
}
*/Advanced Example: Type System for Jurassic Park Infrastructure
Let's look at a more complex example that uses conditional types to model different systems in Jurassic Park:
// --- Basic system types ---
type SystemStatus = "online" | "offline" | "maintenance" | "error";
interface BaseSystem {
id: string;
name: string;
status: SystemStatus;
lastUpdated: Date;
}
// Different types of systems in the park
interface SecuritySystem extends BaseSystem {
type: "security";
enclosures: string[];
alertLevel: "low" | "medium" | "high" | "critical";
cameras: number;
motionSensors: number;
}
interface PowerSystem extends BaseSystem {
type: "power";
outputCapacity: number; // kW
currentLoad: number; // kW
backupCapacity: number; // kW
generators: number;
}
interface TransportSystem extends BaseSystem {
type: "transport";
vehicles: number;
routes: string[];
passengerCapacity: number;
automatedGuidance: boolean;
}
interface LifeSupportSystem extends BaseSystem {
type: "lifesupport";
habitats: string[];
environmentalControls: {
temperature: number; // ยฐC
humidity: number; // %
oxygen: number; // %
};
}
// Union of all system types
type ParkSystem = SecuritySystem | PowerSystem | TransportSystem | LifeSupportSystem;
// --- Conditional types for monitoring data ---
/**
* Conditional type that determines what monitoring data is relevant for each system type
*/
type MonitoringData<T extends ParkSystem> = T extends SecuritySystem
? {
breachDetections: number;
securityFootage: { cameraId: string; timestamp: Date; events: string[] }[];
activeAlarms: string[];
}
: T extends PowerSystem
? {
loadDistribution: { sector: string; load: number }[];
energyEfficiency: number; // %
estimatedBackupTime: number; // hours
powerFluctuations: boolean;
}
: T extends TransportSystem
? {
activeVehicles: number;
passengerCount: number;
delayReports: { routeId: string; delay: number }[];
fuelConsumption: number; // liters/hour
}
: T extends LifeSupportSystem
? {
habitatConditions: {
habitatId: string;
temperature: number;
humidity: number;
oxygenLevel: number;
co2Level: number;
}[];
anomalyDetections: string[];
resourceConsumption: { water: number; electricity: number; air: number };
}
: never; // Fallback for unknown types
/**
* Conditional type determining recommended actions for systems in different states
*/
type RecommendedActions<T extends ParkSystem> =
T extends { status: "error" }
? { severity: "high"; actions: string[]; escalation: string; timeToResolve: number }
: T extends { status: "maintenance" }
? { checklistItems: string[]; estimatedCompletionTime: Date; personnelAssigned: string[] }
: T extends { status: "offline" }
? { restartProcedures: string[]; systemDependencies: string[]; estimatedDowntime: number }
: { routineChecks: string[]; nextMaintenanceDate: Date };
// --- System monitoring class using conditional types ---
/**
* Class managing system monitoring, using conditional types
* to ensure type correctness for different systems
*/
class SystemMonitor<T extends ParkSystem> {
private system: T;
private monitoringData: MonitoringData<T>;
private recommendedActions: RecommendedActions<T>;
constructor(system: T) {
this.system = system;
// Initializing monitoringData based on system type
this.monitoringData = this.initializeMonitoringData();
// Initializing recommendedActions based on system type and status
this.recommendedActions = this.initializeRecommendedActions();
}
// Helper method for initializing monitoring data
private initializeMonitoringData(): MonitoringData<T> {
// Implementation dependent on type T
if (this.system.type === "security") {
return {
breachDetections: 0,
securityFootage: [],
activeAlarms: []
} as MonitoringData<T>;
} else if (this.system.type === "power") {
return {
loadDistribution: [],
energyEfficiency: 95,
estimatedBackupTime: 48,
powerFluctuations: false
} as MonitoringData<T>;
} else if (this.system.type === "transport") {
return {
activeVehicles: 0,
passengerCount: 0,
delayReports: [],
fuelConsumption: 0
} as MonitoringData<T>;
} else if (this.system.type === "lifesupport") {
return {
habitatConditions: [],
anomalyDetections: [],
resourceConsumption: { water: 0, electricity: 0, air: 0 }
} as MonitoringData<T>;
} else {
throw new Error(`Unknown system type: ${(this.system as any).type}`);
}
}
// Helper method for initializing recommended actions
private initializeRecommendedActions(): RecommendedActions<T> {
if (this.system.status === "error") {
return {
severity: "high",
actions: ["Immediate technical intervention", "Notify management"],
escalation: "Technical Director",
timeToResolve: 60 // minutes
} as RecommendedActions<T>;
} else if (this.system.status === "maintenance") {
return {
checklistItems: ["Check the wiring", "Functionality test"],
estimatedCompletionTime: new Date(Date.now() + 3600000), // +1 hour
personnelAssigned: ["Tech-1", "Tech-2"]
} as RecommendedActions<T>;
} else if (this.system.status === "offline") {
return {
restartProcedures: ["Power supply check", "System reset"],
systemDependencies: ["Main power supply"],
estimatedDowntime: 120 // minutes
} as RecommendedActions<T>;
} else {
return {
routineChecks: ["Daily inspection", "Log check"],
nextMaintenanceDate: new Date(Date.now() + 7 * 24 * 3600000) // +7 days
} as RecommendedActions<T>;
}
}
// Method for updating monitoring data
updateMonitoringData(newData: Partial<MonitoringData<T>>): void {
this.monitoringData = { ...this.monitoringData, ...newData };
console.log(`Updated monitoring data for ${this.system.name} (ID: ${this.system.id})`);
}
// Method for generating system report
generateSystemReport(): string {
const report = `
SYSTEM REPORT: ${this.system.name.toUpperCase()} (ID: ${this.system.id})
=========================================================
Type: ${this.system.type}
Status: ${this.system.status}
Last update: ${this.system.lastUpdated.toLocaleString()}
MONITORING DETAILS:
${this.formatMonitoringData()}
RECOMMENDED ACTIONS:
${this.formatRecommendedActions()}
=========================================================
Report generated: ${new Date().toLocaleString()}
`;
return report;
}
// Method for formatting monitoring data depending on system type
private formatMonitoringData(): string {
if (this.system.type === "security") {
const data = this.monitoringData as MonitoringData<SecuritySystem>;
return `
Detected breaches: ${data.breachDetections}
Active alarms: ${data.activeAlarms.length > 0 ? data.activeAlarms.join(", ") : "None"}
Security footage: ${data.securityFootage.length}
`;
} else if (this.system.type === "power") {
const data = this.monitoringData as MonitoringData<PowerSystem>;
return `
Energy efficiency: ${data.energyEfficiency}%
Estimated time on backup power: ${data.estimatedBackupTime} hours
Power fluctuations: ${data.powerFluctuations ? "YES" : "NO"}
Load distribution: ${data.loadDistribution.map(d => `${d.sector}: ${d.load}kW`).join(", ")}
`;
} else if (this.system.type === "transport") {
const data = this.monitoringData as MonitoringData<TransportSystem>;
return `
Active vehicles: ${data.activeVehicles}
Passenger count: ${data.passengerCount}
Fuel consumption: ${data.fuelConsumption} liters/hour
Delay reports: ${data.delayReports.length > 0
? data.delayReports.map(d => `${d.routeId}: ${d.delay}min`).join(", ")
: "No delays"}
`;
} else if (this.system.type === "lifesupport") {
const data = this.monitoringData as MonitoringData<LifeSupportSystem>;
return `
Habitat conditions: ${data.habitatConditions.map(h =>
`${h.habitatId} (Temp: ${h.temperature}ยฐC, Humidity: ${h.humidity}%, O2: ${h.oxygenLevel}%)`).join("\n")}
Detected anomalies: ${data.anomalyDetections.length > 0 ? data.anomalyDetections.join(", ") : "None"}
Resource usage: Water: ${data.resourceConsumption.water}mยณ, Power: ${data.resourceConsumption.electricity}kWh, Air: ${data.resourceConsumption.air}mยณ
`;
} else {
return `No monitoring data for this system type.`;
}
}
// Method for formatting recommended actions depending on system status
private formatRecommendedActions(): string {
if (this.system.status === "error") {
const actions = this.recommendedActions as RecommendedActions<{ status: "error" }>;
return `
Severity level: ${actions.severity}
Recommended actions: ${actions.actions.join(", ")}
Escalation to: ${actions.escalation}
Estimated repair time: ${actions.timeToResolve} minutes
`;
} else if (this.system.status === "maintenance") {
const actions = this.recommendedActions as RecommendedActions<{ status: "maintenance" }>;
return `
Items to check: ${actions.checklistItems.join(", ")}
Estimated completion time: ${actions.estimatedCompletionTime.toLocaleString()}
Assigned personnel: ${actions.personnelAssigned.join(", ")}
`;
} else if (this.system.status === "offline") {
const actions = this.recommendedActions as RecommendedActions<{ status: "offline" }>;
return `
Restart procedures: ${actions.restartProcedures.join(", ")}
System dependencies: ${actions.systemDependencies.join(", ")}
Estimated downtime: ${actions.estimatedDowntime} minutes
`;
} else {
const actions = this.recommendedActions as RecommendedActions<ParkSystem>;
return `
Routine checks: ${actions.routineChecks.join(", ")}
Next inspection: ${actions.nextMaintenanceDate.toLocaleDateString()}
`;
}
}
// Method returning recommended actions
getRecommendedActions(): RecommendedActions<T> {
return this.recommendedActions;
}
// Method for updating system status
updateSystemStatus(newStatus: SystemStatus): void {
(this.system as any).status = newStatus;
this.system.lastUpdated = new Date();
// Updating recommended actions after status change
this.recommendedActions = this.initializeRecommendedActions();
console.log(`Updated status of system ${this.system.name} to ${newStatus}`);
}
}
// --- Example usage ---
// Creating sample systems
const securitySystem: SecuritySystem = {
id: "SEC-001",
name: "Main security system",
status: "online",
lastUpdated: new Date(),
type: "security",
enclosures: ["T-Rex", "Velociraptor", "Dilophosaurus"],
alertLevel: "low",
cameras: 24,
motionSensors: 36
};
const powerSystem: PowerSystem = {
id: "PWR-001",
name: "Main power system",
status: "online",
lastUpdated: new Date(),
type: "power",
outputCapacity: 10000,
currentLoad: 6500,
backupCapacity: 5000,
generators: 4
};
// Creating monitors for different systems
const securityMonitor = new SystemMonitor<SecuritySystem>(securitySystem);
const powerMonitor = new SystemMonitor<PowerSystem>(powerSystem);
// Updating monitoring data
securityMonitor.updateMonitoringData({
breachDetections: 3,
activeAlarms: ["Sector 7G", "Northern fence"],
securityFootage: [
{ cameraId: "CAM-12", timestamp: new Date(), events: ["Motion in restricted area"] }
]
});
powerMonitor.updateMonitoringData({
loadDistribution: [
{ sector: "Visitor Center", load: 2000 },
{ sector: "TRex Paddock", load: 1500 },
{ sector: "Raptor Enclosure", load: 1800 },
{ sector: "Labs", load: 1200 }
],
energyEfficiency: 92,
powerFluctuations: true
});
// Simulating a power system failure
powerMonitor.updateSystemStatus("error");
// Generating reports
console.log(securityMonitor.generateSystemReport());
console.log(powerMonitor.generateSystemReport());
// Checking if recommended actions are of the correct type
const powerActions = powerMonitor.getRecommendedActions();
console.log(`Power failure severity level: ${powerActions.severity}`);
console.log(`Time to resolution: ${powerActions.timeToResolve} minutes`);This elaborate example shows how conditional types can be used to create a complex system that adapts its behavior and data structure depending on the type of object it's working with. This is especially useful when modeling systems that have many variants but share some common functionality.
Limitations of Conditional Types
Although conditional types are a powerful tool, they also have some limitations:
Limited inference capability - TypeScript has limited ability to infer types in complex scenarios, especially when generic types are used together with conditional types.
Type erasure at runtime - like other advanced type features in TypeScript, conditional types exist only at compile time. At runtime, there is no information about conditional types, which can lead to difficulties in implementing certain patterns.
Complexity for beginners - conditional types, especially combined with other advanced type features, can be difficult to understand for TypeScript beginners.
When to Use Conditional Types?
Conditional types are especially useful in the following scenarios:
Creating flexible APIs - when you want your functions or methods to behave differently depending on the type of arguments passed.
Implementing advanced generic tools - when building complex tools that must work with different data types.
Modeling complex business systems - when dealing with different variants of business objects that share common features but differ in details.
Creating type transformation tools - when you need to map one type to another conditionally.
Summary
Conditional types in TypeScript are an advanced but extremely useful tool that allows creating flexible and type-safe APIs. Just as geneticists in Jurassic Park can adapt their protocols to different dinosaur DNA types, conditional types allow us to adapt our code's behavior to different data types while maintaining full support for static typing.
In the following exercises, we will continue exploring advanced features of the TypeScript type system and see how they can help us create safer, more flexible, and easier-to-maintain code.
Code for this lesson: index.ts
// Conditional types - Jurassic Park
console.log("=== CONDITIONAL TYPES ===\n");
// ===========================================
// 1. A basic conditional type
// ===========================================
type IsCarnivore<T> = T extends { diet: "carnivore" } ? true : false;
interface Carnivore {
name: string;
diet: "carnivore";
biteForce: number;
}
interface Herbivore {
name: string;
diet: "herbivore";
favoriteFood: string;
}
// A conditional type is resolved at compile time
type RexCheck = IsCarnivore<Carnivore>; // true
type CeraCheck = IsCarnivore<Herbivore>; // false
// ===========================================
// 2. Extract and Exclude
// ===========================================
type DinosaurType = "T-Rex" | "Velociraptor" | "Triceratops" | "Brachiosaurus" | "Stegosaurus";
// Extract - picking out the matching types
type Predator = Extract<DinosaurType, "T-Rex" | "Velociraptor">;
// Result: "T-Rex" | "Velociraptor"
// Exclude - removing the matching types
type Gentle = Exclude<DinosaurType, "T-Rex" | "Velociraptor">;
// Result: "Triceratops" | "Brachiosaurus" | "Stegosaurus"
// ===========================================
// 3. infer - extracting types from constructs
// ===========================================
type DinosaurData = {
name: string;
stats: { weight: number; height: number; speed: number };
abilities: string[];
};
// Extracting a type from a nested structure
type StatsType = DinosaurData["stats"]; // { weight: number; height: number; speed: number }
// infer in conditional types
type UnpackArray<T> = T extends Array<infer U> ? U : T;
type AbilityType = UnpackArray<DinosaurData["abilities"]>; // string
type UnpackPromise<T> = T extends Promise<infer U> ? U : T;
type ResolvedDino = UnpackPromise<Promise<DinosaurData>>; // DinosaurData
// ===========================================
// 4. ReturnType and Parameters
// ===========================================
function createDinosaur(name: string, weight: number, isDangerous: boolean) {
return {
name,
weight,
isDangerous,
createdAt: new Date()
};
}
type DinoResult = ReturnType<typeof createDinosaur>;
type DinoParams = Parameters<typeof createDinosaur>;
// ===========================================
// 5. NonNullable
// ===========================================
type MaybeDino = string | number | null | undefined;
type DefinitelyDino = NonNullable<MaybeDino>; // string | number
// ===========================================
// 6. Practical example - an API response system
// ===========================================
type ApiResponse<T> = T extends "dinosaur"
? { id: number; name: string; species: string }
: T extends "enclosure"
? { id: number; name: string; capacity: number }
: T extends "staff"
? { id: number; name: string; role: string }
: never;
function getResponse<T extends "dinosaur" | "enclosure" | "staff">(
type: T
): ApiResponse<T> {
if (type === "dinosaur") {
return { id: 1, name: "Rexy", species: "T-Rex" } as ApiResponse<T>;
} else if (type === "enclosure") {
return { id: 101, name: "T-Rex Zone", capacity: 2 } as ApiResponse<T>;
}
return { id: 1001, name: "Alan Grant", role: "Paleontologist" } as ApiResponse<T>;
}
// ===========================================
// Test
// ===========================================
console.log("--- Extract / Exclude ---");
const predator: Predator = "T-Rex";
const gentle: Gentle = "Brachiosaurus";
console.log("Predator:", predator);
console.log("Gentle:", gentle);
console.log("\n--- ReturnType ---");
const dino: DinoResult = createDinosaur("Blue", 15, true);
console.log("Created dinosaur:", JSON.stringify(dino, null, 2));
console.log("\n--- Conditional API Response ---");
const dinoResp = getResponse("dinosaur");
console.log("Dinosaur:", JSON.stringify(dinoResp));
const encResp = getResponse("enclosure");
console.log("Enclosure:", JSON.stringify(encResp));
const staffResp = getResponse("staff");
console.log("Staff member:", JSON.stringify(staffResp));
console.log("\n--- NonNullable ---");
function processDino(value: NonNullable<MaybeDino>): void {
console.log("Value:", value, "Type:", typeof value);
}
processDino("Rexy");
processDino(42);
// processDino(null); // Error!
console.log("\nConditional types = dynamic logic at the type level!");Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What does the conditional type T extends U ? X : Y do in TypeScript?
2. What is the purpose of the infer keyword in conditional types?
These are 2 of 3 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Create conditional types for dynamic type inference
- Click in order
Arrange the elements of a conditional type: