01. keyof and typeof Operators
Less than 1 minute
01. keyof and typeof Operators ๊ด๋ จ
Learn TypeScript > 01. keyof and typeof Operators
01. keyof and typeof Operators
The keyof
type operator works with object types to create a string or numeric literal union of its keys.
The typeof
type operator queries the type of a value, allowing you to refer to it in various places.
let person = {name: "Alice", age: 28};
type Person = typeof person;
type PersonKeys = keyof Person; // "name" | "age"
Exercise
Create a function that updates a property's value in an object, given the object, a property key, and a new value.
Question
function updateProperty<T>(obj: T, key: keyof T, value: any): T {
// Your code here
return obj;
}
console.log(updateProperty({name: "Alice", age: 28}, "name", "Bob"));
Answer
function updateProperty<T>(obj: T, key: keyof T, value: any): T {
// Your code here
return obj;
}
console.log(updateProperty({name: "Alice", age: 28}, "name", "Bob"));