Bird
Raised Fist0
Typescriptprogramming~10 mins

Generic class syntax in Typescript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Generic class syntax
Define Generic Class with <T>
↓
Create Instance with Specific Type
↓
Use Instance Methods/Properties with Type T
↓
Type Safety Ensured at Compile Time
↓
End
This flow shows how a generic class is defined with a placeholder type T, then instantiated with a real type, and used with type safety.
Execution Sample
Typescript
class Box<T> {
  content: T;
  constructor(value: T) {
    this.content = value;
  }
  getContent(): T {
    return this.content;
  }
}

const box = new Box<number>(123);
console.log(box.getContent());
Defines a generic class Box that holds a value of type T, creates a Box of number, and prints its content.
Execution Table
StepActionEvaluationResult
1Define class Box<T>Generic class with type parameter TClass Box<T> created
2Create instance box = new Box<number>(123)T is number, value is 123box.content = 123
3Call box.getContent()Returns content of type numberReturns 123
4console.log outputPrints returned value123 printed to console
5EndNo more codeExecution stops
💡 All steps completed, program ends after printing 123
Variable Tracker
VariableStartAfter Step 2After Step 3Final
box.contentundefined123123123
Key Moments - 3 Insights
Why do we write <T> after the class name?
The <T> declares a placeholder type for the class. It means the class can work with any type, which is set when creating an instance (see execution_table step 1 and 2).
What type does box.content have?
box.content has the type number because we created Box<number> (see variable_tracker and execution_table step 2). This ensures type safety.
What happens if we try to put a string in Box<number>?
TypeScript will give an error because the class expects a number, not a string. This is shown by the type parameter T being fixed to number at instance creation (execution_table step 2).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of box.content after step 2?
A123
B"123" (string)
Cundefined
Dnull
💡 Hint
Check variable_tracker column 'After Step 2' for box.content value.
At which step does the program print the number 123 to the console?
AStep 1
BStep 4
CStep 3
DStep 5
💡 Hint
Look at execution_table row where console.log output happens.
If we change Box<number> to Box<string>, what type will box.content have?
Anumber
Bany
Cstring
Dunknown
💡 Hint
Generic type T is replaced by the type given at instance creation (see concept_flow and execution_table step 2).
Concept Snapshot
Generic class syntax:
class ClassName<T> {
  property: T;
  constructor(value: T) { this.property = value; }
  method(): T { return this.property; }
}
Use: const obj = new ClassName<Type>(value);
Ensures type safety with flexible types.
Full Transcript
This example shows how to define and use a generic class in TypeScript. The class Box has a type parameter T, which acts like a placeholder for any type. When we create an instance of Box, we specify the actual type, like number. The class stores a value of that type and returns it with a method. The execution table traces each step: defining the class, creating an instance with number, calling the method, and printing the result. The variable tracker shows how box.content changes from undefined to 123. Key moments clarify why we use <T>, what type box.content has, and what happens if we try to use the wrong type. The quiz tests understanding of variable values, output timing, and type substitution. The snapshot summarizes the syntax and usage for quick reference.

Practice

(1/5)
1. What does the <T> mean in a TypeScript generic class declaration like class Box<T> {}?
easy
A. It declares a placeholder type that can be replaced with any type when creating an instance.
B. It defines a fixed type named T that cannot be changed.
C. It is a syntax error and should be removed.
D. It specifies that the class only works with numbers.

Solution

  1. Step 1: Understand generic type parameter

    The <T> after the class name declares a generic type parameter named T, which acts as a placeholder for any type.
  2. Step 2: Purpose of generic classes

    This allows the class to work flexibly with any type specified when creating an instance, making the code reusable and type-safe.
  3. Final Answer:

    It declares a placeholder type that can be replaced with any type when creating an instance. -> Option A
  4. Quick Check:

    Generic <T> = placeholder type [OK]
Hint: Generic <T> means flexible type placeholder [OK]
Common Mistakes:
  • Thinking <T> fixes the type permanently
  • Confusing generic syntax with inheritance
  • Assuming <T> is a variable or value
2. Which of the following is the correct syntax to declare a generic class named Container with a type parameter T?
easy
A. class Container[T] {}
B. class Container(T) {}
C. class Container {T} {}
D. class Container<T> {}

Solution

  1. Step 1: Recall generic class syntax

    In TypeScript, generic classes use angle brackets <> to declare type parameters after the class name.
  2. Step 2: Match correct syntax

    The correct syntax is class Container<T> {}. Other options use parentheses, curly braces, or square brackets incorrectly.
  3. Final Answer:

    class Container<T> {} -> Option D
  4. Quick Check:

    Generic class uses <T> syntax [OK]
Hint: Generic classes use angle brackets <T> after name [OK]
Common Mistakes:
  • Using parentheses instead of angle brackets
  • Placing type parameter inside class body
  • Using square brackets which are for arrays
3. What is the output of this TypeScript code?
class Box<T> {
  content: T;
  constructor(value: T) {
    this.content = value;
  }
  getContent(): T {
    return this.content;
  }
}

const box = new Box<string>('hello');
console.log(box.getContent());
medium
A. Box { content: 'hello' }
B. undefined
C. hello
D. TypeError at runtime

Solution

  1. Step 1: Understand class instantiation

    The class Box<T> is instantiated with T = string, so content is a string holding 'hello'.
  2. Step 2: Trace method call

    The method getContent() returns the stored content, which is 'hello'. The console.log prints this string.
  3. Final Answer:

    hello -> Option C
  4. Quick Check:

    Generic class returns stored value 'hello' [OK]
Hint: Generic class returns stored value of specified type [OK]
Common Mistakes:
  • Expecting object print instead of string
  • Confusing property with method output
  • Thinking generic causes runtime error
4. Identify the error in this generic class code:
class Pair<T, U> {
  first: T;
  second: U;
  constructor(first: T, second: T) {
    this.first = first;
    this.second = second;
  }
}
medium
A. Constructor parameters should be (first: T, second: U) to match property types.
B. Generic parameters should be declared as <T> only, not .
C. Properties first and second must have the same type T.
D. Constructor cannot have parameters in a generic class.

Solution

  1. Step 1: Compare constructor parameters with property types

    The class declares two generic types T and U, with properties first: T and second: U.
  2. Step 2: Identify mismatch in constructor

    The constructor incorrectly uses second: T instead of second: U, causing a type mismatch.
  3. Final Answer:

    Constructor parameters should be (first: T, second: U) to match property types. -> Option A
  4. Quick Check:

    Constructor params must match generic property types [OK]
Hint: Match constructor param types to generic properties [OK]
Common Mistakes:
  • Using same type for both parameters ignoring generics
  • Removing one generic parameter incorrectly
  • Thinking constructor can't have parameters in generics
5. You want to create a generic class Dictionary<K, V> that stores key-value pairs. Which implementation correctly uses generics to store and retrieve values by key?
class Dictionary<K, V> {
  private items: Map<K, V> = new Map();

  add(key: K, value: V): void {
    this.items.set(key, value);
  }

  get(key: K): V | undefined {
    return this.items.get(key);
  }
}
hard
A. Generic types cannot be used with Map in TypeScript.
B. This implementation correctly uses generics to store and retrieve values by key.
C. The add method should return the value added, not void.
D. The Map should be declared as Map<V, K> to match key-value order.

Solution

  1. Step 1: Analyze Map usage with generics

    The class uses Map<K, V> to store keys of type K and values of type V, which is correct.
  2. Step 2: Check methods for correct generic usage

    The add method sets a key-value pair, and get retrieves the value by key, both using the generic types properly.
  3. Final Answer:

    This implementation correctly uses generics to store and retrieve values by key. -> Option B
  4. Quick Check:

    Generic Map<K, V> with add/get methods = correct [OK]
Hint: Use Map with add/get methods for generic dictionary [OK]
Common Mistakes:
  • Swapping key and value types in Map declaration
  • Expecting add to return a value unnecessarily
  • Believing generics can't be used with built-in types
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