← All Exercises

Variance in Generic Types

advancedtypescript~30min

Background

Variance rules determine type compatibility for generics, critical for understanding type assignment safety.

Problem

Demonstrate covariance in arrays (Animal[] accepts Dog[]) and contravariance in function parameters with typed examples.

Input

Class hierarchy with Animal as supertype and Dog as subtype.

Output

Demonstration of which assignments are type-safe and which are not.

Sample tests

Sample 1

Input: Dog[] assigned to Animal[]
Expected: Allowed (covariant)

Your solution

Learning objective

Understand covariance and contravariance in TypeScript generic type compatibility.