Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
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.
✗ Incorrect
The generic function uses a parameter named 'param' of type T to return the same value.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'string' as constraint limits to string only, not all types with length.
Using 'any' removes the constraint.
✗ Incorrect
The generic type T is constrained to types that have a 'length' property of type number.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'object' does not guarantee 'toString' method signature.
Using 'string' as constraint is incorrect here.
✗ Incorrect
The constraint requires T to have a 'toString' method returning a string.
4fill in blank
hardFill 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'
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.
✗ Incorrect
The key parameter is of type K which extends keys of T, and the return type is the value type at key K.
5fill in blank
hardFill 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'
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.
✗ Incorrect
The function accesses obj[key], checks if it's an object with a length property, and returns length or 0 if not present.