0
0
Typescriptprogramming~10 mins

Type erasure and its consequences 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 function that returns the input value.

Typescript
function identity<T>(value: [1]): T {
  return value;
}
Drag options to blanks, or click blank then click option'
Anumber
Bany
CT
Dstring
Attempts:
3 left
💡 Hint
Common Mistakes
Using a fixed type like 'number' instead of the generic type parameter.
Using 'any' which loses type safety.
2fill in blank
medium

Complete the code to create a generic array and push a value into it.

Typescript
let items: Array<[1]> = [];
items.push(42);
Drag options to blanks, or click blank then click option'
Astring
Bobject
Cboolean
Dnumber
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'string' or other types that don't match the pushed value.
Using 'object' which is too general.
3fill in blank
hard

Fix the error in the function that tries to access a property of a generic type without constraints.

Typescript
function getLength<T>(arg: T): number {
  return arg.[1];
}
Drag options to blanks, or click blank then click option'
Alength
Bsize
Ccount
Dlength()
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'length()' as if it were a method.
Using 'size' or 'count' which are not standard properties on strings or arrays.
4fill in blank
hard

Fill both blanks to constrain the generic type to have a length property and return that length.

Typescript
function loggingIdentity<T extends [1]>(arg: T): number {
  return arg.[2];
}
Drag options to blanks, or click blank then click option'
A{ length: number }
Bstring
Clength
Dnumber
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'string' as a constraint which is too specific.
Using 'length()' as a method call.
5fill in blank
hard

Fill all three blanks to create a generic function that returns the keys of an object as an array of strings.

Typescript
function getObjectKeys<T extends object>(obj: T): Array<[1]> {
  return Object.[2](obj) as Array<[3]>;
}
Drag options to blanks, or click blank then click option'
Astring
Bkeys
Dvalues
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'values' instead of 'keys'.
Using 'number' instead of 'string' for the array type.