0
0
Typescriptprogramming~5 mins

Generic constraints with extends in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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): void
It 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?
AT can be any type
BT must be a subtype of U
CU must be a subtype of T
DT and U must be the same type
Which of these is a valid generic constraint to require a length property?
A<code>&lt;T extends boolean&gt;</code>
B<code>&lt;T extends number&gt;</code>
C<code>&lt;T extends { length: number }&gt;</code>
D<code>&lt;T extends string&gt;</code>
What error occurs if you pass a number to function f<T extends { name: string }>(obj: T)?
AType 'number' is not assignable to type '{ name: string }'
BRuntime error
CNo error
DSyntax error
Why use generic constraints instead of concrete types?
ATo allow more flexible and reusable code
BTo make code slower
CTo avoid type checking
DTo restrict code to one type only
Which of these is a correct way to declare a generic function with a constraint?
Afunction example&lt;T&gt;(arg: T extends { id: number }): void {}
Bfunction example&lt;T&gt;(arg: T): T extends { id: number }
Cfunction example(arg: T extends { id: number }): void {}
Dfunction example&lt;T extends { id: number }&gt;(arg: T): void {}
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>&lt;T extends { length: number }&gt;</code> and access <code>obj.length</code>.
    You got /3 concepts.