Recall & Review
beginner
What does the
extends keyword do in TypeScript generics?It limits the types that a generic can accept by requiring the type to be a subtype of the specified type or interface.
Click to reveal answer
beginner
How do you write a generic function that only accepts objects with a
name property of type string?Use a generic constraint like
<T extends { name: string }> to ensure the type has a name property of type string.Click to reveal answer
intermediate
Why use generic constraints with
extends instead of just using a specific type?Generic constraints allow flexibility by accepting any type that meets the condition, making code reusable while still ensuring type safety.
Click to reveal answer
beginner
What happens if you try to use a type that does not satisfy the
extends constraint?TypeScript will show a compile-time error because the type does not meet the required structure or properties.
Click to reveal answer
beginner
Example: What does this function signature mean?<br>
function logName<T extends { name: string }>(obj: T): voidIt means the function
logName accepts an object obj of any type T as long as T has a name property of type string.Click to reveal answer
What does
T extends U mean in TypeScript generics?✗ Incorrect
T extends U means T must be a subtype or satisfy the structure of U.
Which of these is a valid generic constraint to require a
length property?✗ Incorrect
Only <T extends { length: number }> ensures the type has a length property.
What error occurs if you pass a number to
function f<T extends { name: string }>(obj: T)?✗ Incorrect
TypeScript shows a compile-time error because number does not have a name property.
Why use generic constraints instead of concrete types?
✗ Incorrect
Generic constraints allow flexibility while keeping type safety.
Which of these is a correct way to declare a generic function with a constraint?
✗ Incorrect
Option D correctly uses extends in the generic parameter list.
Explain how generic constraints with
extends help in writing safer TypeScript code.Think about how you tell TypeScript what kind of types are allowed.
You got /4 concepts.
Write a simple generic function using
extends to accept only objects with a length property.Use <code><T extends { length: number }></code> and access <code>obj.length</code>.
You got /3 concepts.