November 2019
Beginner
804 pages
20h 1m
English
The keyof operator is also called the index type query operator. It returns permitted property names for the given type. This operator is useful when you want to make sure that a given name is actually a valid key of some type.
This happens quite often in the JavaScript ecosystem, for example, when APIs accept property names as parameters and later access those properties using the someObject[propertyName] syntax.
Let's look at an example of how to use keyof in practice:
interface Game { name: string; players: number; } function displayGameProperty(game: Game, propertyName: keyof Game): void { console.log(game[propertyName]); } const game: Game = {name: "Chess", players: 2}; displayGameProperty(game,"name"); //displayGameProperty(game, ...Read now
Unlock full access