0
0
Typescriptprogramming~10 mins

Covariance and contravariance 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 covariant array of strings.

Typescript
let fruits: ReadonlyArray<string> = ['apple', 'banana', 'cherry'];
let moreFruits: ReadonlyArray<[1]> = fruits;
Drag options to blanks, or click blank then click option'
Aboolean
Bnumber
Cstring
Dany
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different type like number or boolean causes a type error.
Trying to assign a mutable array instead of ReadonlyArray.
2fill in blank
medium

Complete the function type to accept a parameter contravariantly.

Typescript
type Handler = (input: [1]) => void;

let handleString: Handler = (text: string) => console.log(text);
Drag options to blanks, or click blank then click option'
Aany
Bnumber
Cstring
Dunknown
Attempts:
3 left
💡 Hint
Common Mistakes
Using string makes the parameter invariant, not contravariant.
Using number or unknown causes type errors.
3fill in blank
hard

Fix the error in the assignment by choosing the correct type for the function parameter.

Typescript
type Func = (arg: [1]) => void;

let funcString: Func = (s: string) => console.log(s);
let funcAny: Func = funcString;
Drag options to blanks, or click blank then click option'
Aany
Bunknown
Cnumber
Dstring
Attempts:
3 left
💡 Hint
Common Mistakes
Using string causes a type error.
Using number or unknown is incorrect here.
4fill in blank
hard

Fill both blanks to create a covariant return type and contravariant parameter type in the function signature.

Typescript
type Transformer = (input: [1]) => [2];

let transform: Transformer = (value) => value.toString();
Drag options to blanks, or click blank then click option'
Aany
Bstring
Cnumber
Dunknown
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping parameter and return types.
Using the same type for both parameter and return.
5fill in blank
hard

Fill all three blanks to define a function type with contravariant parameter, covariant return, and assign it correctly.

Typescript
type FuncType = (param: [1]) => [2];

let func: FuncType = (x: [3]) => x.toString();
Drag options to blanks, or click blank then click option'
Aany
Bstring
Cnumber
Dunknown
Attempts:
3 left
💡 Hint
Common Mistakes
Using the same type for parameter and assigned function parameter.
Mismatch between return types.