0
0
Typescriptprogramming~10 mins

How TypeScript infers generic types - Interactive Practice

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

Complete the code to define a generic function that returns the input value.

Typescript
function identity<T>([1]: T): T {
  return [1];
}
Drag options to blanks, or click blank then click option'
Avalue
Btype
Cinput
Darg
Attempts:
3 left
💡 Hint
Common Mistakes
Using a parameter name that doesn't match the return statement.
Using a non-generic type.
2fill in blank
medium

Complete the code to call the generic function with a string argument and let TypeScript infer the type.

Typescript
const result = identity([1]);
Drag options to blanks, or click blank then click option'
A42
Bnull
Ctrue
D'hello'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing a number or boolean instead of a string.
Passing null which is not inferred as a string.
3fill in blank
hard

Fix the error in the generic function call by specifying the type explicitly.

Typescript
const result = identity<[1]>(42);
Drag options to blanks, or click blank then click option'
Aboolean
Bstring
Cnumber
Dany
Attempts:
3 left
💡 Hint
Common Mistakes
Specifying a type that doesn't match the argument type.
Omitting the generic type when explicit specification is needed.
4fill in blank
hard

Fill both blanks to define a generic function that returns the length of an array of generic type T.

Typescript
function getLength<[1]>(arr: [2][]): number {
  return arr.length;
}
Drag options to blanks, or click blank then click option'
AT
BU
DV
Attempts:
3 left
💡 Hint
Common Mistakes
Using different generic type names for the parameter and array element.
Not using a generic type for the array elements.
5fill in blank
hard

Fill all three blanks to create a generic function that returns the first element of an array of generic type T or undefined if empty.

Typescript
function firstElement<[1]>(arr: [2][]): [3] | undefined {
  return arr.length > 0 ? arr[0] : undefined;
}
Drag options to blanks, or click blank then click option'
AT
BU
DV
Attempts:
3 left
💡 Hint
Common Mistakes
Using different generic type names for parameters and return type.
Not including undefined in the return type.