1. Welcome and Icebreaker:
- If you could set up a rule that changes based on a condition, what would it be?
2. Outline the Session:
- We’ll learn about conditional types in TypeScript and how to use them with generics.
- Learning Outcomes: Understand how to use conditional types to create flexible and type-safe APIs.
- Let’s get conditional!
3. Concept Explanation:
- Conditional Types use the
extends keyword and a ternary-like syntax to choose a type based on a condition.
- Syntax:
type IsString<T> = T extends string ? true : false;
- Useful for creating types that depend on other types.
- Can be combined with generics for powerful type logic.
4. Live Coding Demonstration:
type IsArray<T> = T extends any[] ? true : false;
console.log<IsArray<string>>(); // false
console.log<IsArray<number[]>>(); // true
// Conditional type for extracting type
type ElementType<T> = T extends (infer U)[] ? U : T;
type A = ElementType<string[]>; // string
type B = ElementType<number>; // number
// Conditional type with generics
function getTypeName<T>(value: T): string {
if (Array.isArray(value)) return "array";
return typeof value;
}
console.log(getTypeName([1, 2, 3])); // "array"
console.log(getTypeName("hello")); // "string"
5. Tasks:
- Short Exercise:
- Write a conditional type
IsNumber<T> that is true if T is number, otherwise false.
- Write a type
ReturnTypeOrNever<T> that extracts the return type of a function type, or never if not a function.
- Test your types with different examples.