Generic Types
Generic Types
π¨βπΌ Generics aren't just for functionsβyou can create reusable, generic types
and interfaces too!
// Generic type alias
type Container<Value> = {
value: Value
}
// Generic interface
interface Box<Contents> {
contents: Contents
}
// Usage
const stringBox: Box<string> = { contents: 'hello' }
const numberBox: Box<number> = { contents: 42 }
This is exactly how built-in types like
Array<Item> and Promise<ResponseData>
work.π¦ Avoid using generics to hide a cast. This is a common anti-pattern:
// β Bad: the caller picks the type, not the data
function getData<Data>(): Data {
return fetchData() as Data
}
const user = getData<User>() // Compiles even if fetchData returns wrong shape!
This compiles even if the actual data is the wrong shape, which defeats the
purpose of TypeScript. Instead, you should actually validate the data and use
type guards to ensure the data is the correct shape.
π¨ Open
and:
- Create a generic
LoadingState<Data>type for async operations - Create helper functions
createSuccess<Data>andcreateError<Data> - See how TypeScript narrows the type based on the discriminated union
π° Model idle, loading, success, and error states with a generic discriminated union.