Bird
Raised Fist0
Typescriptprogramming~20 mins

Generic class with constraints in Typescript - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Generic Class Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of a generic class with constraint
What is the output of this TypeScript code when creating an instance of Container with a Person object?
Typescript
interface HasName {
  name: string;
}

class Container<T extends HasName> {
  private item: T;
  constructor(item: T) {
    this.item = item;
  }
  getName(): string {
    return this.item.name;
  }
}

class Person {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
}

const person = new Person("Alice");
const container = new Container(person);
console.log(container.getName());
Aundefined
B"Alice"
CTypeError at runtime
DCompilation error due to missing property
Attempts:
2 left
💡 Hint
Look at the constraint T extends HasName and what property Person has.
❓ Predict Output
intermediate
2:00remaining
What error occurs with invalid generic type?
What error will this TypeScript code produce when trying to create a Container with a Car object?
Typescript
interface HasName {
  name: string;
}

class Container<T extends HasName> {
  private item: T;
  constructor(item: T) {
    this.item = item;
  }
  getName(): string {
    return this.item.name;
  }
}

class Car {
  model: string;
  constructor(model: string) {
    this.model = model;
  }
}

const car = new Car("Tesla");
const container = new Container(car);
ACompilation error: Type 'Car' does not satisfy the constraint 'HasName'.
BNo error, but getName() returns undefined
COutput: "Tesla"
DRuntime error: Cannot read property 'name' of undefined
Attempts:
2 left
💡 Hint
Check if Car has the required name property.
🔧 Debug
advanced
2:00remaining
Why does this generic class cause a runtime error?
This TypeScript code compiles but throws an error at runtime. What causes the error?
Typescript
interface HasName {
  name: string;
}

class Container<T extends HasName> {
  private item: T;
  constructor(item: T) {
    this.item = item;
  }
  printName(): void {
    console.log(this.item.name.toUpperCase());
  }
}

const obj = { name: null };
const container = new Container(obj);
container.printName();
ARuntime error because 'name' is null and has no method 'toUpperCase()'.
BCompilation error because 'name' can be null.
CNo error; prints 'NULL' as string.
DRuntime error because 'item' is undefined.
Attempts:
2 left
💡 Hint
Consider the value of name and what toUpperCase() expects.
📝 Syntax
advanced
2:00remaining
Identify the syntax error in this generic class declaration
Which option correctly fixes the syntax error in this TypeScript generic class?
Typescript
interface HasId {
  id: number;
}

class Repository<T HasId> {
  private items: T[] = [];
  add(item: T): void {
    this.items.push(item);
  }
}
ARemove <code>HasId</code> constraint entirely
BChange <code>class Repository<T HasId></code> to <code>class Repository<T implements HasId></code>
CChange <code>T HasId</code> to <code>T extends HasId</code>
DAdd colon: <code>class Repository<T: HasId></code>
Attempts:
2 left
💡 Hint
TypeScript uses a specific keyword for generic constraints.
🚀 Application
expert
2:00remaining
How many items are stored after filtering with generic constraint?
Given this generic class that filters items with a status property, how many items remain after filtering?
Typescript
interface HasStatus {
  status: string;
}

class Filterer<T extends HasStatus> {
  private items: T[];
  constructor(items: T[]) {
    this.items = items;
  }
  filterActive(): T[] {
    return this.items.filter(item => item.status === 'active');
  }
}

const data = [
  { status: 'active', id: 1 },
  { status: 'inactive', id: 2 },
  { status: 'active', id: 3 },
  { status: 'pending', id: 4 }
];

const filterer = new Filterer(data);
const activeItems = filterer.filterActive();
console.log(activeItems.length);
A3
B4
C1
D2
Attempts:
2 left
💡 Hint
Count how many objects have status exactly equal to 'active'.

Practice

(1/5)
1. What is the main purpose of using constraints in a generic class in TypeScript?
easy
A. To ensure the generic type has specific properties or methods
B. To make the class run faster
C. To allow any type without restrictions
D. To convert the generic type to a string

Solution

  1. Step 1: Understand generic constraints

    Constraints limit the types that can be used with a generic to those having certain properties or methods.
  2. Step 2: Identify the purpose of constraints

    This ensures the generic class can safely use those properties or methods without errors.
  3. Final Answer:

    To ensure the generic type has specific properties or methods -> Option A
  4. Quick Check:

    Constraints = limit types by properties/methods [OK]
Hint: Constraints limit types to those with needed features [OK]
Common Mistakes:
  • Thinking constraints improve performance
  • Believing constraints allow any type
  • Confusing constraints with type conversion
2. Which of the following is the correct syntax to declare a generic class with a constraint that T must have a 'length' property?
easy
A. class Box {}
B. class Box {}
C. class Box {}
D. class Box {}

Solution

  1. Step 1: Recall TypeScript generic constraint syntax

    TypeScript uses extends keyword to constrain generics.
  2. Step 2: Match syntax for property constraint

    To require a property, use an object type with that property, e.g., { length: number }.
  3. Final Answer:

    class Box<T extends { length: number }> {} -> Option D
  4. Quick Check:

    Generic constraints use extends with type shape [OK]
Hint: Use 'extends' with object type for constraints [OK]
Common Mistakes:
  • Using 'where' or 'with' keywords (not valid in TypeScript)
  • Using colon ':' instead of 'extends'
  • Omitting the property type in constraint
3. What will be the output of the following TypeScript code?
class Container<T extends { name: string }> {
  item: T;
  constructor(item: T) {
    this.item = item;
  }
  getName() {
    return this.item.name;
  }
}

const obj = { name: 'Box', size: 10 };
const c = new Container(obj);
console.log(c.getName());
medium
A. undefined
B. 'Box'
C. Error: Property 'name' does not exist
D. null

Solution

  1. Step 1: Analyze the generic constraint and object

    The class requires T to have a 'name' string property. The object has 'name' and 'size', so it fits.
  2. Step 2: Understand method getName()

    It returns this.item.name, which is 'Box' from the object.
  3. Final Answer:

    'Box' -> Option B
  4. Quick Check:

    Accessing constrained property returns 'Box' [OK]
Hint: Check if object matches constraint properties [OK]
Common Mistakes:
  • Assuming extra properties cause errors
  • Thinking output is undefined if extra props exist
  • Confusing runtime errors with compile-time checks
4. Identify the error in this TypeScript generic class declaration:
class DataHolder<T extends number | string> {
  value: T;
  constructor(value: T) {
    this.value = value;
  }
  printValue() {
    console.log(this.value.toFixed(2));
  }
}
medium
A. toFixed is not available on string type
B. Generic constraint syntax is incorrect
C. Missing return type for printValue method
D. Constructor parameter type mismatch

Solution

  1. Step 1: Check the generic constraint

    T can be number or string, so value can be either type.
  2. Step 2: Analyze method printValue()

    It calls toFixed(2), which exists on number but not on string. TypeScript will produce a compile-time error because toFixed is not available on all possible types for T.
  3. Final Answer:

    toFixed is not available on string type -> Option A
  4. Quick Check:

    Method uses number-only function on union type [OK]
Hint: Check method compatibility with all constraint types [OK]
Common Mistakes:
  • Ignoring union type method availability
  • Thinking constraint syntax is wrong
  • Assuming missing return type causes error here
5. You want to create a generic class KeyValueStore that only accepts types with a key property of type string and a value property of any type. Which of the following is the correct way to declare this class?
hard
A. class KeyValueStore<T with key: string, value: any> { constructor(public item: T) {} }
B. class KeyValueStore<T> where T has key: string, value: any { constructor(public item: T) {} }
C. class KeyValueStore<T extends { key: string; value: any }> { constructor(public item: T) {} }
D. class KeyValueStore<T: { key: string; value: any }> { constructor(public item: T) {} }

Solution

  1. Step 1: Recall TypeScript generic constraint syntax

    Use extends with an object type to constrain T to have specific properties.
  2. Step 2: Match the required properties

    The constraint must require key: string and value: any properties.
  3. Step 3: Verify constructor syntax

    The constructor correctly accepts an item of type T and assigns it.
  4. Final Answer:

    class KeyValueStore<T extends { key: string; value: any }> { constructor(public item: T) {} } -> Option C
  5. Quick Check:

    Use extends with object type for property constraints [OK]
Hint: Use 'extends' with object type for property constraints [OK]
Common Mistakes:
  • Using 'where' or 'with' keywords (not valid in TypeScript)
  • Using colon ':' instead of 'extends'
  • Omitting property types in constraint
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