Bird
Raised Fist0
Typescriptprogramming~10 mins

Generic type variance in Typescript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Generic type variance
Define generic types
↓
Assign generic with subtype
↓
Check variance rules
↓
Allowed
↓
Use safely
↓
End
This flow shows how generic types are defined, assigned with subtypes, checked for variance rules, and either allowed or rejected.
Execution Sample
Typescript
interface Animal { name: string }
interface Dog extends Animal { bark(): void }

function feedAnimals<T extends Animal>(animals: T[]): void {
  animals.forEach(a => console.log(a.name));
}

const dogs: Dog[] = [{ name: 'Rex', bark: () => {} }];
feedAnimals(dogs);
This code defines generic function feedAnimals that accepts arrays of Animal or its subtypes, then calls it with Dog array.
Execution Table
StepActionGeneric Type TInput ValueType Check ResultOutput/Effect
1Define interface AnimalN/AN/AN/AAnimal has property name:string
2Define interface Dog extends AnimalN/AN/AN/ADog adds bark() method
3Define function feedAnimals<T extends Animal>T extends AnimalN/AN/AGeneric function accepts array of T
4Create dogs arrayDog[{name:'Rex', bark:()=>{}}]Dog[] is subtype of Animal[]?Yes, Dog extends Animal
5Call feedAnimals(dogs)T = Dogdogs arrayT extends Animal check passesPrints 'Rex'
6Inside feedAnimals, forEach prints a.nameT = DogEach dog objectAccess name propertyOutput: Rex
7End of functionN/AN/AN/AFunction completes successfully
💡 Execution stops after printing all animal names; type checks ensure safe use of subtypes.
Variable Tracker
VariableStartAfter Step 4After Step 5Final
dogsundefined[{name:'Rex', bark:()=>{}}][{name:'Rex', bark:()=>{}}][{name:'Rex', bark:()=>{}}]
TundefinedDogDogDog
Key Moments - 3 Insights
Why can we pass Dog[] to a function expecting Animal[] when Dog extends Animal?
Because Dog is a subtype of Animal, arrays of Dog are compatible with arrays of Animal in this generic context, as shown in execution_table row 4 and 5.
What happens if we try to assign Animal[] to a variable of type Dog[]?
This causes a type error because Animal[] may contain animals that are not Dogs, violating type safety. This is the opposite variance and is not allowed.
Why does the generic constraint T extends Animal matter here?
It ensures that T has at least the properties of Animal, so inside feedAnimals we can safely access a.name, as shown in execution_table row 6.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 5, what is the generic type T inferred as?
AAnimal
BDog
Cstring
Dunknown
💡 Hint
Check the 'Generic Type T' column at step 5 in execution_table.
At which step does the program print the dog's name?
AStep 3
BStep 4
CStep 6
DStep 7
💡 Hint
Look for the 'Output/Effect' column mentioning printing in execution_table.
If we remove 'extends Animal' from generic T, what would happen?
ATypeScript would allow any type for T, risking errors when accessing a.name
BThe code would work exactly the same
CThe code would fail to compile because T is unknown
DThe function would only accept Animal arrays
💡 Hint
Consider the role of 'T extends Animal' in the generic constraint from key_moments.
Concept Snapshot
Generic type variance lets you use subtypes safely in generics.
Use 'T extends BaseType' to restrict generics.
Subtypes can be passed where base types expected.
This ensures safe access to properties/methods.
Violating variance causes type errors.
Full Transcript
This visual execution traces generic type variance in TypeScript. We define Animal and Dog interfaces, where Dog extends Animal. A generic function feedAnimals accepts arrays of type T constrained to Animal or its subtypes. We create a Dog array and pass it to feedAnimals. The type checker confirms Dog[] is compatible with Animal[]. Inside the function, we safely access the name property. The execution table shows each step, variable states, and type checks. Key moments clarify why subtypes work and the importance of constraints. The quiz tests understanding of type inference, output timing, and constraint roles.

Practice

(1/5)
1.

Which of the following best describes covariance in TypeScript generic types?

easy
A. It allows a generic type to accept a supertype where a subtype is expected.
B. It allows a generic type to accept a subtype where a supertype is expected.
C. It restricts generic types to only accept exact types without substitution.
D. It means generic types cannot be assigned to each other regardless of relation.

Solution

  1. Step 1: Understand covariance meaning

    Covariance means you can use a more specific type (subtype) where a more general type (supertype) is expected.
  2. Step 2: Apply to generic types

    In TypeScript, covariance allows substituting a subtype for a supertype safely in generics.
  3. Final Answer:

    It allows a generic type to accept a subtype where a supertype is expected. -> Option B
  4. Quick Check:

    Covariance = subtype for supertype [OK]
Hint: Covariance means subtype can replace supertype [OK]
Common Mistakes:
  • Confusing covariance with contravariance
  • Thinking covariance restricts substitution
  • Assuming covariance means exact type only
2.

Which of the following is the correct syntax to declare a generic function with contravariant parameter in TypeScript?

function process<T>(input: T): void { /* ... */ }
easy
A. function process(input: T): void { }
B. function process(input: T): void { }
C. function process<T>(input: T): void { }
D. function process(input: T): void { }

Solution

  1. Step 1: Recall TypeScript generic variance syntax

    TypeScript does not use in or out keywords like some languages for variance.
  2. Step 2: Check valid generic function syntax

    The correct syntax is simply function process<T>(input: T): void { } without variance keywords.
  3. Final Answer:

    function process<T>(input: T): void { } -> Option C
  4. Quick Check:

    No variance keywords in TypeScript generics [OK]
Hint: TypeScript uses no in/out keywords for generics [OK]
Common Mistakes:
  • Using in/out keywords from other languages
  • Trying to extend non-existent variance types
  • Assuming variance is declared in generic syntax
3.

Consider the following TypeScript code:

interface Animal { name: string; }
interface Dog extends Animal { bark(): void; }

function feedAnimals(animals: ReadonlyArray<Animal>) { /* ... */ }

const dogs: Dog[] = [{ name: 'Rex', bark: () => console.log('Woof!') }];
feedAnimals(dogs);

What is the output or result of calling feedAnimals(dogs)?

medium
A. It causes a compile-time error due to type incompatibility.
B. It compiles but silently ignores the dogs array.
C. It runs but throws a runtime error because of type mismatch.
D. It compiles and runs without error because ReadonlyArray is covariant.

Solution

  1. Step 1: Understand ReadonlyArray variance

    ReadonlyArray in TypeScript is covariant, so Dog[] can be used where ReadonlyArray<Animal> is expected.
  2. Step 2: Check function call validity

    Passing dogs (Dog[]) to feedAnimals(animals: ReadonlyArray<Animal>) is allowed and compiles without error.
  3. Final Answer:

    It compiles and runs without error because ReadonlyArray is covariant. -> Option D
  4. Quick Check:

    ReadonlyArray is covariant = safe assignment [OK]
Hint: ReadonlyArray is covariant, so subtype arrays pass [OK]
Common Mistakes:
  • Assuming arrays are invariant by default
  • Confusing mutable arrays with ReadonlyArray
  • Expecting runtime errors from type mismatch
4.

Identify the error in the following TypeScript code related to generic variance:

interface Printer<T> {
  print(value: T): void;
}

const animalPrinter: Printer<Animal> = {
  print: (animal: Animal) => console.log(animal.name)
};

const dogPrinter: Printer<Dog> = animalPrinter;
dogPrinter.print({ name: 'Buddy', bark: () => console.log('Woof!') });
medium
A. Assigning animalPrinter to dogPrinter causes a type error due to invariance.
B. The print method signature is incorrect and causes a syntax error.
C. There is no error; the code runs and prints 'Buddy'.
D. The dogPrinter variable is not declared properly.

Solution

  1. Step 1: Analyze variance of Printer<T>

    Printer<T> has a method accepting T as parameter, making it contravariant in T.
  2. Step 2: Check assignment direction

    Assigning Printer<Animal> to Printer<Dog> is invalid because contravariance requires the opposite direction.
  3. Final Answer:

    Assigning animalPrinter to dogPrinter causes a type error due to invariance. -> Option A
  4. Quick Check:

    Function parameter generics are contravariant [OK]
Hint: Function parameters are contravariant; assignment direction matters [OK]
Common Mistakes:
  • Ignoring contravariance in function parameters
  • Assuming generic interfaces are always covariant
  • Confusing parameter and return type variance
5.

You want to create a generic event handler interface in TypeScript that accepts events of type T. The handler should be able to accept handlers for supertypes of T (contravariance). Which of the following interface declarations correctly models this behavior?

hard
A. type EventHandler<T> = (event: T) => void;
B. interface EventHandler<in T> { handle(event: T): void; }
C. interface EventHandler<T> { handle(event: T): T; }
D. interface EventHandler<T> { handle(event: T): void; }

Solution

  1. Step 1: Understand contravariance in function parameters

    Function parameters are contravariant, so a function type like (event: T) => void models contravariance naturally.
  2. Step 2: Compare interface and type alias

    Interfaces with methods are invariant by default in TypeScript, but function types are contravariant in parameters, so using a type alias for a function is correct.
  3. Step 3: Check invalid syntax options

    interface EventHandler<in T> { handle(event: T): void; } uses in keyword which TypeScript does not support; interface EventHandler<T> { handle(event: T): T; } changes return type, losing contravariance.
  4. Final Answer:

    type EventHandler<T> = (event: T) => void; -> Option A
  5. Quick Check:

    Function types are contravariant in parameters [OK]
Hint: Use function types for contravariant parameters [OK]
Common Mistakes:
  • Using unsupported 'in' keyword in generics
  • Assuming interfaces are contravariant by default
  • Changing return type affects variance incorrectly
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