by Headway
Advanced TypeScript tutorial on type guards, utility functions (lookup, extract, omit, conditional), generics, and practical examples
A comprehensive TypeScript tutorial covering type guards (in operator, type predicates, assert functions), utility types (lookup, extract, omit, conditional), and generics. Includes practical examples for working with union types, API responses, and component props.
Use the 'in' operator to check if a property exists in an object. This helps TypeScript narrow down union types at runtime.
For a document type that can be either 'delimited' (has 'separator') or 'plain text' (no separator), check if 'separator' exists in the object before passing to functions that require it.
Define functions with 'is TypeName' return type to perform type narrowing. The function returns true if the condition is met, allowing TypeScript to narrow the type.
Example: function isFinalInvoice(invoice: Invoice): invoice is FinalInvoice { return invoice.typeName === 'finalInvoice'; }
Use assert functions with 'asserts value is Type' syntax to validate types and throw clear errors when validation fails.
Example: function assertNumber(value: unknown): asserts value is number { if (typeof value !== 'number') throw new Error('Not a number'); }
Use the Extract utility type to pull specific members from union types based on pattern matching.
Extract<T, U> returns the types in T that are assignable to U. Useful for separating different shapes in code-generated union types.
Use ternary syntax in type definitions with 'extends' keyword to create types that evaluate based on conditions.
Example: type Engine<T> = T extends { engine: infer E } ? E : never; This extracts the engine type from objects that have one.
Create a type helper that unwraps array types to get the element type using conditional types and infer.
type Unarray<T> = T extends Array<infer U> ? U : T;
Use Omit<Type, Keys> to create types that exclude specific properties from a base type.
Useful for component props where you want to allow most MUI Button props but exclude specific ones like 'variant'.
Pass generic types to component props to allow flexible prop types while maintaining type safety.
Use ButtonProps from Material UI with generics to create branded buttons that accept all button props except ones you want to restrict.