TypeScript Covariance and Contravariance
Covariance and contravariance are important concepts in the TypeScript type system; understanding them helps you write type-safe code.
They describe how generic types behave in parent-child type relationships.
Why covariance and contravariance are needed
When we use generic classes or functions, the behavior of type parameters is not as simple as you might think.
Assigning a Dog to an Animal is safe, but assigning a function that handles Animal to one that handles Dog may be unsafe.
The rules of covariance and contravariance help TypeScript catch these potential type errors.
Concept:Covariance allows a subtype to convert to a supertype, contravariance allows a supertype to convert to a subtype, and invariance allows no conversion in either direction.
Covariant
Covariance means a subtype can be assigned to a supertype. For output types (such as function return values), this is safe.
Example
// Define types for animals and dogs
class
Animal
{
name
:
string
=
"Animal"
;
}
class
Dog
extends
Animal
{
breed
:
string
=
"Rural dog"
;
}
// Covariance: output types can convert to broader types
// A function returning Dog can be assigned to a function returning Animal
type AnimalGetter
=
(
)
=>
Animal
;
type DogGetter
=
(
)
=>
Dog
;
// Dog is a subtype of Animal, so DogGetter can be assigned to AnimalGetter
const
getDog
:
DogGetter
=
(
)
=>
new
Dog
(
)
;
const
getAnimal
:
AnimalGetter
=
getDog
;
// Covariance: safe
// Run
const
animal
:
Animal
=
getAnimal
(
)
;
console.
log
(
"Animal name: "
animal.
name
)
;
Running result:
动物名称: 动物
Return value covariance:It is safe for a function to return a more specific subtype, because the returned object necessarily satisfies the supertype's requirements.
Contravariant
Contravariance means that for input types (such as function parameters), a supertype can be assigned to a subtype.
Example
// Define types
class
Animal
{
name
:
string
=
"Animal"
;
}
class
Dog
extends
Animal
{
breed
:
string
=
"Rural dog"
;
}
// Contravariance: input types can convert to more specific types
// A function accepting Animal can be assigned to a function accepting Dog
type DogConsumer
=
(
dog
:
Dog
)
=>
void
;
type AnimalConsumer
=
(
animal
:
Animal
)
=>
void
;
// If a function accepting a broader type can be assigned to one accepting a more specific type
// then when we pass in a Dog, the function may not be able to handle it (lacking Dog-specific properties)
const
consumeAnimal
:
AnimalConsumer
=
(
animal
)
=>
{
console.
log
(
"Handle animal: "
animal.
name
)
;
}
;
const
consumeDog
:
DogConsumer
=
consumeAnimal
;
// Contravariance: safe
// Run
const
dog
=
new
Dog
(
)
;
dog.
breed
=
"Husky"
;
consumeDog
(
dog
)
;
Parameter contravariance:Function parameters use contravariance because a function accepting a more specific type cannot handle a broader type.
Enable strict function types
TypeScript checks function parameters contravariantly by default. Enabling strictFunctionTypes enforces this rule.
Example
// Define types
interface
Animal
{
readonly name
:
string
;
}
interface
Dog
extends
Animal
{
readonly breed
:
string
;
}
// Define function types
type GetName
=
(
animal
:
Animal
)
=>
string
;
type GetDogBreed
=
(
dog
:
Dog
)
=>
string
;
// Correct assignment
const
getDogBreed
:
GetDogBreed
=
(
dog
)
=>
dog.
breed
;
// Attempted assignment - will error under strictFunctionTypes
// Because AnimalConsumer (broader parameter) cannot be assigned to DogConsumer (more specific parameter)
// This is because parameters are contravariant
function
printAnimalName
(
animal
:
Animal
)
:
string
{
return
animal.
name
;
}
// Attempt to assign a function accepting a broader type to a more specific type
// const getSpecific: GetDogBreed = printAnimalName; // Error!
console.
log
(
"Dog breed: "
getDogBreed
(
{
name
:
"Wangcai"
,
breed
:
"Husky"
}
)
)
;
strictFunctionTypes:Enabling this option in tsconfig.json gives you stricter type checking.
Covariance in generic classes
Properties of generic classes are covariant by default.
Example
// Define types
class
Animal
{
name
:
string
=
"Animal"
;
}
class
Dog
extends
Animal
{
breed
:
string
=
"Dog"
;
}
// Generic container class
class
Cage
<
T
{
animal:
T
;
constructor
(
animal
:
T
)
{
this
.
animal
=
animal
;
}
}
// Covariance: a subtype container can be assigned to a supertype container
const
dogCage
=
new
Cage
(
new
Dog
(
)
)
;
const
animalCage
:
Cage
<
Animal
=
dogCage;
// Covariance: safe
// animalCage can now be safely used as a cage containing animals
console.
log
(
"Animal name: "
animalCage.
animal
.
name
)
;
Property covariance:Object properties are covariant; a subtype property can be assigned to a supertype property.
Array covariance
Arrays in TypeScript are covariant, but you need to watch for issues caused by mutability.
Example
// Define types
class
Animal
{
name
:
string
=
"Animal"
;
}
class
Dog
extends
Animal
{
breed
:
string
=
"Dog"
;
}
// Array covariance
const
dogs
:
Dog
[
]
=
[
{
name
:
"Wangcai"
,
breed
:
"Husky"
}
,
{
name
:
"Xiaobai"
,
breed
:
"Samoyed"
}
]
;
// Dog[] can be assigned to Animal[]
const
animals
:
Animal
[
]
=
dogs
;
// Covariance: safe
// Problem: although type-safe, you can still add other animals
// animals.push({ name: "Cat", breed: "Cat" }); // May cause problems at runtime!
console.
log
(
"Animal count: "
animals.
length
)
;
Array mutability:Modifying an array after a covariant assignment may cause runtime errors, so be careful.
Using extends for safe assignment
Once you understand covariance and contravariance, you can design generic interfaces safely.
Example
// Define types
interface
Producer
<
T
{// Producer method: return value is covariant
produce
(
)
:
T
;
}
interface
Consumer
<
T
{// Consumer method: parameter is contravariant
consume
(
value
:
T
)
:
void
;
}
// Concrete implementation
class
DogProducer
implements
Producer
<
Dog
{
produce
(
):
Dog
{
return
{
name
:
"Wangcai"
,
breed
:
"Husky"
}
;
}
}
class
AnimalConsumer
implements
Consumer
<
Animal
{
consume
(
animal:
Animal
)
:
void
{
console.
log
(
"Consume animal: "
animal.
name
)
;
}
}
// Producer
const
animalProducer
:
Producer
<
Animal
=
new
DogProducer
(
);
// Consumer
const
dogConsumer
:
Consumer
<
Dog
=
new
AnimalConsumer
(
);
// Test
const
animal
=
animalProducer.
produce
(
)
;
console.
log
(
"Produce: "
animal.
name
)
;
dogConsumer.
consume
(
{
name
:
"Wangcai"
,
breed
:
"Husky"
}
)
;
Design principle:Choose the appropriate type direction based on a method's purpose to improve API type safety.
Notes
- **Return value covariance:** It is safe for a function to return a subtype
- **Parameter contravariance:** It is safe for function parameters to use a supertype
- **Enable strict mode:** Use strictFunctionTypes for stricter checking
- **Array covariance:** Watch for potential issues from mutability
Best practices:Understanding covariance and contravariance helps you design more type-safe APIs and avoid runtime errors.
Summary
Covariance and contravariance are core concepts of the TypeScript type system.
- **Covariance:** subtype → supertype, used for output types
- **Contravariance:** supertype → subtype, used for input types
- **Invariance:** cannot be assigned to each other
- **strictFunctionTypes:** enable strict function type checking
Note:Consider covariance and contravariance when designing generic APIs to write safer type code.