Bird
Raised Fist0
Typescriptprogramming~5 mins

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

Choose your learning style10 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?
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.

      Practice

      (1/5)
      1.

      What does the extends keyword do in a TypeScript generic constraint?

      easy
      A. It limits the generic type to types that match a specific shape or interface.
      B. It makes the generic type optional.
      C. It allows the generic type to be any type without restriction.
      D. It converts the generic type to a string.

      Solution

      1. Step 1: Understand the role of extends in generics

        The extends keyword in generics restricts the generic type to only those types that satisfy a certain condition, usually matching an interface or type shape.
      2. Step 2: Compare with other options

        Options B, C, and D describe behaviors unrelated to extends in generics. It does not make types optional, allow any type, or convert types to strings.
      3. Final Answer:

        It limits the generic type to types that match a specific shape or interface. -> Option A
      4. Quick Check:

        Generic constraints = limit type shape [OK]
      Hint: Remember: extends restricts generic types to certain shapes [OK]
      Common Mistakes:
      • Thinking extends makes a type optional
      • Confusing extends with type conversion
      • Assuming extends removes restrictions
      2.

      Which of the following is the correct syntax to constrain a generic type T to an object with a name property of type string?

      function greet<T>(obj: T): string {
      return `Hello, ${obj.name}`;
      }
      easy
      A. function greet<T>(obj: T extends { name: string }): string
      B. function greet<T extends { name: string }>(obj: T): string
      C. function greet<T = { name: string }>(obj: T): string
      D. function greet<T>(obj: T & { name: string }): string

      Solution

      1. Step 1: Identify correct generic constraint syntax

        The correct way to constrain a generic type is using T extends { name: string } inside the angle brackets.
      2. Step 2: Check other options for syntax errors

        function greet<T = { name: string }>(obj: T): string uses assignment (=) which is for default types, not constraints. function greet<T>(obj: T extends { name: string }): string misplaces extends outside the angle brackets. function greet<T>(obj: T & { name: string }): string uses intersection (&) in parameter type, which is valid but not a generic constraint.
      3. Final Answer:

        function greet<T extends { name: string }>(obj: T): string -> Option B
      4. Quick Check:

        Use extends inside <> for constraints [OK]
      Hint: Use extends inside <> for constraints [OK]
      Common Mistakes:
      • Using = instead of extends for constraints
      • Placing extends outside generic brackets
      • Confusing intersection types with constraints
      3.

      What will be the output of this TypeScript code?

      interface HasId { id: number; }
      function getId<T extends HasId>(obj: T): number {
      return obj.id;
      }
      const item = { id: 42, name: 'Book' };
      console.log(getId(item));
      medium
      A. Error: Type argument does not satisfy constraint
      B. undefined
      C. Error: Property 'id' does not exist
      D. 42

      Solution

      1. Step 1: Check if item satisfies the constraint

        The interface HasId requires an id property of type number. The object item has id: 42, so it satisfies T extends HasId.
      2. Step 2: Understand function behavior

        The function returns obj.id, so calling getId(item) returns 42.
      3. Final Answer:

        42 -> Option D
      4. Quick Check:

        Object matches constraint, returns id [OK]
      Hint: Check if argument matches constraint to predict output [OK]
      Common Mistakes:
      • Assuming runtime error due to missing explicit type
      • Confusing property existence with type errors
      • Thinking generic constraints affect runtime output
      4.

      Identify the error in this TypeScript code and select the fix:

      function printLength<T>(arg: T): number {
      return arg.length;
      }
      medium
      A. Add constraint: <T extends { length: number }>
      B. Change return type to void
      C. Remove length property access
      D. Use any instead of generic T

      Solution

      1. Step 1: Identify cause of error

        The generic type T has no guarantee to have a length property, so accessing arg.length causes a compile error.
      2. Step 2: Fix by adding a constraint

        Adding T extends { length: number } ensures arg has a length property, fixing the error.
      3. Final Answer:

        Add constraint: <T extends { length: number }> -> Option A
      4. Quick Check:

        Constraint ensures property exists [OK]
      Hint: Add extends constraint to guarantee properties exist [OK]
      Common Mistakes:
      • Ignoring missing property errors
      • Changing return type instead of fixing constraint
      • Using any defeats generic safety
      5.

      Given this interface and function, which call is valid and why?

      interface Person {
      name: string;
      age: number;
      }

      function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
      return obj[key];
      }

      const person: Person = { name: 'Alice', age: 30 };

      Which call is valid?

      hard
      A. getProperty(person, 0)
      B. getProperty(person, 'height')
      C. getProperty(person, 'name')
      D. getProperty(person, 'toString')

      Solution

      1. Step 1: Understand the generic constraints

        The function uses K extends keyof T, so the key must be a valid property name of T. For Person, valid keys are 'name' and 'age'.
      2. Step 2: Evaluate each option

        getProperty(person, 'name') uses 'name', which is a valid key. getProperty(person, 'height') uses 'height', not in Person. getProperty(person, 0) uses 0, not a key. getProperty(person, 'toString') uses 'toString', which is a method on Object prototype, not a key of Person interface.
      3. Final Answer:

        getProperty(person, 'name') -> Option C
      4. Quick Check:

        Key must be keyof object type [OK]
      Hint: Use keys from interface only with keyof constraint [OK]
      Common Mistakes:
      • Using keys not declared in interface
      • Passing numbers instead of string keys
      • Confusing prototype methods with interface keys
      Recommended

      Ready to prove it?

      Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

      10 questions~5 mineasy hard