Restricting string choices with keyof

The use of string in JavaScript is omnipresent. One pattern is to access a member of an object dynamically with the square bracket:

interface Human {
name: string;
birthdate: Date;
isHappy: boolean;
}

const me: Human = {
name: "Patrick",
birthdate: new Date(1912, 0, 1),
isHappy: true
}

console.log(me["name"]);

The problem with the code is that name is a string and could be anything. We could set between brackets firstname, and the code would compile. At runtime, the console would show undefined. To avoid falling into the pitfall of selecting a member that does not exist, we can use keyof, which will return a union of all members of an object. The union is a string literal of all members' names.

Before going with keyof, create a function that tries to access a property by a string fail, without defining an index signature (see Index signature in this book):

function showMe1(obj: Human, field: string): void {
console.log(obj[field]); // Does not compile
}

However, the same function with keyof will work without an index signature. The reason is that TypeScript knows that you do not try to access a field that might not exist. The goal of accessing with the square bracket is to access members that exist:

function showMe2(obj: Human, field: keyof Human): void {
console.log(obj[field]);
}

The keyof allows specifying in a string format the only field from the type after the keyof keyword. In the code example before, only the string name, birthdate and isHappy can be entered without having the compiler show an error:

showMe2(me, "name"); // Compile
showMe2(me, "NOname"); // Does not compile
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.106.225