0
0
Typescriptprogramming~10 mins

Keyof operator 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 type that represents the keys of the Person interface.

Typescript
interface Person { name: string; age: number; }
type PersonKeys = [1] Person;
Drag options to blanks, or click blank then click option'
Akey
Bkeys
Ckeyof
Dtypeof
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'typeof' instead of 'keyof' which gets the type of a variable, not keys.
Using 'keys' which is not a valid TypeScript operator.
2fill in blank
medium

Complete the function signature to accept only keys of the User type.

Typescript
type User = { id: number; username: string; };
function getUserProperty(user: User, key: [1] User) {
  return user[key];
}
Drag options to blanks, or click blank then click option'
Anumber
Bkeyof
Cstring
Dany
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'string' which allows any string, not just keys of User.
Using 'any' which disables type checking.
3fill in blank
hard

Fix the error in the code by completing the type for the keys parameter.

Typescript
interface Product { name: string; price: number; }
function getProperty(obj: Product, keys: [1] Product) {
  return obj[keys];
}
Drag options to blanks, or click blank then click option'
Akeyof
Bstring
Cnumber
Dany
Attempts:
3 left
💡 Hint
Common Mistakes
Typing keys as 'string' which is too broad and causes errors.
Using 'any' which disables type safety.
4fill in blank
hard

Fill both blanks to create a function that returns the value of a given key from an object.

Typescript
function getValue<T, K extends [1] T>(obj: T, key: K): T[[2]] {
  return obj[key];
}
Drag options to blanks, or click blank then click option'
Akeyof
Bstring
CK
Dnumber
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'string' instead of 'keyof' for the constraint.
Using 'string' or 'number' instead of the generic key type for indexing.
5fill in blank
hard

Fill all three blanks to define a generic function that safely gets a property value by key.

Typescript
function safeGet<T, K extends [1] T>(obj: T, key: K): T[[2]] {
  if (key in obj) {
    return obj[[3]];
  }
  throw new Error('Key not found');
}
Drag options to blanks, or click blank then click option'
Akeyof
BK
Ckey
Dstring
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'string' instead of 'keyof' for the constraint.
Using 'string' instead of the generic key type for indexing.
Using a wrong variable name instead of 'key' inside the function.