Constraints with extends and review
An unconstrained generic accepts any type, and for that very reason you can do almost nothing with it: inside a function with a plain T, the compiler only knows that T is something. You cannot ask for its length property or compare it with another value. To work with generic values you need to tell the compiler which minimal features the type must have. This is done with a constraint, written with the extends keyword inside the angle brackets: T extends something means T can be any type that satisfies that something.
// function lengthOf<T>(value: T): number { return value.length; } // error: Property 'length' does not exist on type 'T'
function lengthOf<T extends { length: number }>(value: T): number {
return value.length;
}
console.log(lengthOf('hello')); // 5
console.log(lengthOf([1, 2, 3])); // 3
// lengthOf(42); // error: 'number' does not satisfy the constraint '{ length: number; }'
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
console.log(longest('ab', 'abc'), longest([1], [1, 2, 3]));What is valuable about the constraint is that the concrete type is preserved: longest('ab', 'abc') returns a string, not just an object with length. Compare it with writing the function receiving { length: number } without a generic: the result would lose the original type. The constraint sets a floor; the generic keeps everything else.
Constraining a key with keyof
A very frequent constraint is that a parameter must be a valid key of another. The keyof T operator produces the union of property names of T. With K extends keyof T, the function getProperty(obj, key) only accepts keys that really exist on obj, and returns exactly the type of that property, T[K]. Writing a nonexistent key is a compile error, and autocompletion offers the possible keys. We will go deeper into keyof in week 7, but this pattern is already useful today.
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const person = { name: 'Ana', age: 31, active: true };
const name = getProperty(person, 'name'); // string
const age = getProperty(person, 'age'); // number
// getProperty(person, 'email'); // error: Argument of type '"email"' is not assignable to parameter of type '"name" | "age" | "active"'
interface HasId {
id: number;
}
function findById<T extends HasId>(items: T[], id: number): T | undefined {
return items.find((item) => item.id === id);
}
console.log(name, age, findById([{ id: 1, title: 'A' }, { id: 2, title: 'B' }], 2));Week review
This week you went from concrete types to types as parameters: generic functions, generic interfaces and aliases, generic classes, type defaults and constraints with extends and keyof. The key to not getting lost is to read the signature like a sentence: for any T with such a shape, I receive this and return that. Practice with the final exercise and take the quiz to consolidate.
If a generic feels confusing, a useful trick is to mentally replace T with a concrete type and read the signature again. getProperty<T, K>(obj: T, key: K) with T equal to Person and K equal to 'age' becomes getProperty(obj: Person, key: 'age'): number. That substitution almost always clarifies what the function does. And remember the golden rule: use a generic when you relate types between inputs and outputs, not out of habit. Simple code with concrete types is better than an unnecessary generic.
Teste dein Wissen
Frage 1 von 6What does function f<T extends { id: number }>(x: T) mean?
✎ Meine Notizen
Nur in diesem Browser gespeichert. Melde dich an, um es im Konto zu behalten.0/5000 Zeichen