0
0
Typescriptprogramming~10 mins

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

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