Generic Constraints

Constraints
πŸ‘¨β€πŸ’Ό Sometimes you need to limit what types can be used with a generic. For example, a function that accesses .length only works with types that have a length property.
// ❌ Error: Value might not have .length
function logLength<Value>(value: Value) {
	console.log(value.length)
}

// βœ… Constrain Value to types with length
function logLength<Value extends { length: number }>(value: Value) {
	console.log(value.length) // Safe!
}

logLength('hello') // βœ… strings have length
logLength([1, 2, 3]) // βœ… arrays have length
logLength(42) // ❌ Error: number has no length
Use extends to add constraints.
🐨 Open
index.ts
and:
  1. Create a constrained function that requires objects with an id property
  2. Use keyof constraint for type-safe property access (we'll cover type operators in depth in the Advanced TypeScript workshop)
  3. Create a function with multiple constrained type parameters
This is a small preview of type operators. We'll dive deeper into these in the Advanced TypeScript workshop.
keyof ObjectType produces a union of all property names of type ObjectType. For example, if ObjectType is { name: string; age: number }, then keyof ObjectType is 'name' | 'age'.
ObjectType[Key] is an indexed access type - it gives you the type of property Key on type ObjectType. If ObjectType is { name: string } and Key is 'name', then ObjectType[Key] is string.

Please set the playground first

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