0
0
Typescriptprogramming~10 mins

Generic conditional constraints 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 accepts a parameter of any type.

Typescript
function identity<T>([1]: T): T {
  return param;
}
Drag options to blanks, or click blank then click option'
Aparam
Bvalue
Citem
Darg
Attempts:
3 left
💡 Hint
Common Mistakes
Using a parameter name different from the one returned causes an error.
Forgetting to specify the parameter type T.
2fill in blank
medium

Complete the code to constrain the generic type to only types that have a 'length' property.

Typescript
function logLength<T extends [1]>(item: T): number {
  return item.length;
}
Drag options to blanks, or click blank then click option'
A{ length: number }
Bstring
Cnumber
Dany
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'string' as constraint limits to string only, not all types with length.
Using 'any' removes the constraint.
3fill in blank
hard

Fix the error in the generic function that requires T to have a 'toString' method.

Typescript
function stringify<T extends [1]>(value: T): string {
  return value.toString();
}
Drag options to blanks, or click blank then click option'
Aobject
Bstring
C{ toString: () => string }
Dany
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'object' does not guarantee 'toString' method signature.
Using 'string' as constraint is incorrect here.
4fill in blank
hard

Fill both blanks to create a generic function that accepts an object with a key K and returns its value.

Typescript
function getProperty<T, K extends keyof T>(obj: T, key: [1]): T[[2]] {
  return obj[key];
}
Drag options to blanks, or click blank then click option'
AK
Bstring
Ckeyof T
DT
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'string' or 'keyof T' directly in the parameter type causes errors.
Mismatching the key type and return type.
5fill in blank
hard

Fill all three blanks to define a generic function that returns the length of a property K of object T, where that property has a length.

Typescript
function getLength<T, K extends keyof T>(obj: T, key: K): number {
  const value = obj[[1]];
  if (value && typeof value === [2] && 'length' in value) {
    return value.length[3];
  }
  return 0;
}
Drag options to blanks, or click blank then click option'
Akey
B'object'
C?? 0
D'string'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'string' instead of 'object' in typeof check.
Not using nullish coalescing operator causes runtime errors if length is undefined.