Sub topic 1
Subtyping and Assignability: Dog and Animal
Prerequisites
You should know TypeScript interfaces, classes, generics, structural typing, and the strict compiler option. This chapter uses assignability, which is the compiler's rule for deciding whether one value can be used where another type is expected.
Subtyping and assignability
A subtype has at least the capabilities of its supertype. Dog extends Animal, so every Dog can be used as an Animal. The reverse is unsafe because an Animal might not have Dog-specific behavior.
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
const dog: Dog = new Dog();
const animal: Animal = dog; // OK
// const anotherDog: Dog = animal; // Error: bark() is not guaranteedGeneric variance describes whether this relationship carries through a generic type.
Covariance: types that produce values
A generic type is covariant when it only produces values of its type parameter. If a producer can produce a Dog, it can safely be used as a producer of Animal, because every Dog is an Animal.
interface Producer<T> {
get(): T;
}
declare const dogs: Producer<Dog>;
const animals: Producer<Animal> = dogs; // OKThe reverse assignment is unsafe. A Producer<Animal> might produce an animal that is not a dog.
Contravariance: types that consume values
A generic type is contravariant when it only consumes values. A consumer that accepts any Animal can also accept a Dog, so it can be used where a dog consumer is required.
interface Consumer<T> {
accept(value: T): void;
}
declare const animalConsumer: Consumer<Animal>;
const dogConsumer: Consumer<Dog> = animalConsumer; // OKA consumer that accepts only dogs cannot safely replace a consumer that may receive any animal.
Invariance: types that both read and write
A type is invariant when it both produces and consumes its parameter. Neither direction is safe, because an assignment could allow a value of the wrong subtype to be written.
interface Box<T> {
get(): T;
set(value: T): void;
}
declare const dogBox: Box<Dog>;
// const animalBox: Box<Animal> = dogBox; // ErrorExercise
Can Producer<Animal> be assigned to Producer<Dog>?
Show answer
No. It might produce an Animal that is not a Dog.