There are times in a project where you will have an object such as:
const colors = {
red: "#FF0000",
green: "#00FF00",
blue: "#0000FF"
};
And you want to create a type that represents the keys of that object. In this case, you want a type that represents the strings "red", "green", and "blue". This is where keyof comes in.
type ColorKeys = keyof typeof colors;
// ColorKeys is now "red" | "green" | "blue"
keyof is a TypeScript operator that takes an object type and returns a union of its keys. In the example above, keyof typeof colors gives us a type that is a union of the keys of the colors object.
keyof = keys of an object type typeOf = type of a value
You can use this type to create functions that only accept valid keys of the object:
function getColor(key: ColorKeys): string {
return colors[key];
}
const red = getColor("red"); // "#FF0000"
const purple = getColor("purple"); // Error: Argument of type '"purple"' is not assignable to parameter of type 'ColorKeys'.