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
index.ts
and:
  1. Create a generic LoadingState<Data> type for async operations
  2. Create helper functions createSuccess<Data> and createError<Data>
  3. See how TypeScript narrows the type based on the discriminated union
πŸ’° Model idle, loading, success, and error states with a generic discriminated union.

Please set the playground first

Loading "Generic Types"
Loading "Generic Types"
Login to get access to the exclusive discord channel.
Loading Discord Posts