Complete the code to declare a type that represents the keys of the Person interface.
interface Person { name: string; age: number; }
type PersonKeys = [1] Person;The keyof operator creates a union type of the keys of the given type. Here, it extracts 'name' | 'age' from Person.
Complete the function signature to accept only keys of the User type.
type User = { id: number; username: string; };
function getUserProperty(user: User, key: [1] User) {
return user[key];
}The parameter key should be restricted to keys of User using keyof User.
Fix the error in the code by completing the type for the keys parameter.
interface Product { name: string; price: number; }
function getProperty(obj: Product, keys: [1] Product) {
return obj[keys];
}The parameter keys must be typed as keyof Product to ensure it matches one of the property names.
Fill both blanks to create a function that returns the value of a given key from an object.
function getValue<T, K extends [1] T>(obj: T, key: K): T[[2]] { return obj[key]; }
The generic type K extends keyof T to ensure it is a key of T. The return type is T[K], the type of the property.
Fill all three blanks to define a generic function that safely gets a property value by key.
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'); }
The generic K extends keyof T. The return type is T[K]. Inside the function, we use the parameter key to access the property.