0
0
Typescriptprogramming~10 mins

Default generic types 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 define a generic function with a default type.

Typescript
function identity<T = [1]>(arg: T): T {
  return arg;
}
Drag options to blanks, or click blank then click option'
Aboolean
Bnumber
Cany
Dstring
Attempts:
3 left
💡 Hint
Common Mistakes
Using a specific type like string or number as default when flexibility is needed.
2fill in blank
medium

Complete the code to create a generic class with a default type.

Typescript
class Box<T = [1]> {
  contents: T;
  constructor(value: T) {
    this.contents = value;
  }
}
Drag options to blanks, or click blank then click option'
Astring
Bnumber
Cboolean
Dunknown
Attempts:
3 left
💡 Hint
Common Mistakes
Using number or boolean when the example expects string.
3fill in blank
hard

Fix the error in the generic function by adding a default type.

Typescript
function wrapValue<T[1]>(value: T): T[] {
  return [value];
}
Drag options to blanks, or click blank then click option'
A extends string
B extends number
C = number
D = string
Attempts:
3 left
💡 Hint
Common Mistakes
Using extends instead of = for default types.
4fill in blank
hard

Fill both blanks to create a generic interface with a default type and a property using that type.

Typescript
interface Container<T = [1]> {
  value: [2];
}
Drag options to blanks, or click blank then click option'
Anumber
Bstring
CT
Dboolean
Attempts:
3 left
💡 Hint
Common Mistakes
Using the property type as a concrete type instead of the generic parameter.
5fill in blank
hard

Fill all three blanks to define a generic function with two type parameters, one with a default, and return a tuple.

Typescript
function pair<T, U = [1]>(first: T, second: U): [[2], [3]] {
  return [first, second];
}
Drag options to blanks, or click blank then click option'
Astring
BT
CU
Dnumber
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up the order of generic parameters in the return type.