Recall & Review
beginner
What is covariance in TypeScript?
Covariance means you can use a more specific type than expected. For example, if a function expects a type, you can give it a subtype. It works like a "child" fitting where a "parent" is expected.
Click to reveal answer
beginner
What is contravariance in TypeScript?
Contravariance means you can use a more general type than expected. For example, if a function expects a subtype, you can give it a supertype. It is like accepting a broader category where a specific one is expected.
Click to reveal answer
intermediate
Explain covariance with function return types.
Function return types are covariant. This means a function that returns a subtype can be used where a function returning a supertype is expected. It is safe because the caller expects a general type but gets a more specific one.
Click to reveal answer
intermediate
Explain contravariance with function parameter types.
Function parameter types are contravariant. This means a function that accepts a supertype can be used where a function expecting a subtype is required. It is safe because the function can handle more general inputs.
Click to reveal answer
beginner
Why is understanding covariance and contravariance important in TypeScript?
It helps you write flexible and safe code. You can substitute types correctly in functions and variables without errors. It also helps understand how TypeScript checks type compatibility.
Click to reveal answer
Which of the following is an example of covariance in TypeScript?
✗ Incorrect
Covariance applies to return types, allowing a function to return a more specific type than expected.
Contravariance in TypeScript applies mainly to:
✗ Incorrect
Contravariance applies to function parameter types, allowing broader types to be accepted.
If a function expects a parameter of type 'Dog', which parameter type can be used contravariantly?
✗ Incorrect
Contravariance allows using a supertype (Animal) where a subtype (Dog) is expected.
Why is covariance safe for function return types?
✗ Incorrect
The caller expects a general type but receives a more specific one, which is safe.
Which statement about TypeScript variance is true?
✗ Incorrect
Function parameters are contravariant, meaning they accept broader types.
Describe covariance and contravariance in your own words with simple examples.
Think about how types can be substituted in function parameters and return values.
You got /3 concepts.
Explain why function return types are covariant and function parameter types are contravariant in TypeScript.
Consider what happens if you give a function a more general or more specific type.
You got /3 concepts.