0
0
Typescriptprogramming~10 mins

Generic type variance in Typescript - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a generic interface with a covariant type parameter.

Typescript
interface Box<[1] T> {
  value: T;
}
Drag options to blanks, or click blank then click option'
Amutable
Bin
Creadonly
Dout
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'in' instead of 'out' for covariance.
Omitting the variance keyword.
2fill in blank
medium

Complete the code to declare a generic interface with a contravariant type parameter.

Typescript
interface Consumer<[1] T> {
  consume(item: T): void;
}
Drag options to blanks, or click blank then click option'
Ain
Bout
Creadonly
Dmutable
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'out' instead of 'in' for contravariance.
Confusing input and output roles.
3fill in blank
hard

Fix the error in the function signature to correctly use variance with generic types.

Typescript
function copy<[1] T>(source: ReadonlyArray<T>, destination: Array<T>): void {
  for (const item of source) {
    destination.push(item);
  }
}
Drag options to blanks, or click blank then click option'
Aout
Bin
Creadonly
Dmutable
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'in' which is for contravariance and causes errors here.
Omitting variance keyword causing type errors.
4fill in blank
hard

Fill both blanks to create a generic interface with one covariant and one contravariant type parameter.

Typescript
interface Transformer<[1] Input, [2] Output> {
  transform(input: Input): Output;
}
Drag options to blanks, or click blank then click option'
Ain
Bout
Creadonly
Dmutable
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping 'in' and 'out' keywords.
Using 'readonly' or 'mutable' which are not variance keywords.
5fill in blank
hard

Fill all three blanks to define a generic function with correct variance annotations for parameters and return type.

Typescript
function compose<[1] A, [2] B, [3] C>(
  f: (input: A) => B,
  g: (input: B) => C
): (input: A) => C {
  return (input: A) => g(f(input));
}
Drag options to blanks, or click blank then click option'
Ain
Bout
Creadonly
Dmutable
Attempts:
3 left
💡 Hint
Common Mistakes
Marking all type parameters as 'in' or 'out' incorrectly.
Confusing input and output roles in function types.