Typescript: The keyof operator

- 2 min read

A few primary concepts around Typescript help you build complex data shapes. One of that building blocks is the keyof operator.

This operator or keyword is the Typescript’s anwser to the javascript Object.keys operator.

Object.keys returns a list of the properties (the keys) of an object. keyof do something similar but in the typed world only. It will return a literal union type listing the “properties” of an object-like type.

This operator is the base building block for advanced typing like mapped and conditional types.

sponsor

El contenido de este sitio es y será siempre gratuito para todos. Ayudame a mantenerlo así convirtiendote en auspiciador.
Matias Hernández Logo

Tu producto o servicio podría estar aquí

typescript
					
						
type Colors = {
    primary: '#eee',
    primaryBorder: '#444',
    secondary: '#007bff'
    black: '#000',
    white: '#fff',
    whiteBorder: '#f2f2f7',
    green: '#53C497',
    darkGreen: '#43A17C',
    infoGreen: '#23AEB7',
    pastelLightGreen: '#F3FEFF',
}

type ColorKeys = keyof Colors; // "primary" | "primaryBorder" | "secondary" ....

function SomeComponent({ color }: { color: ColorKeys }) {
  return "Something"
}

SomeComponent({ color: "WhateverColor"})

SomeComponent({ color: "primary"})
					
				

The previous code sample is an snippet from a real web app. The Colors type describes a set of colors that can be used across the application.

The keyof operator is applied to the Colors type to retrieve a literal union of all the possible colors.

The union is then used to type the props of SomeComponent, allowing the color argument to be one of the colors defined in the type.

You can also use the keyof operator to build up more complex types or constraints alongside Generics and template literals, but that will be for another post.

There you go; the keyof operator can be small but is an essential piece in the big scheme that unlocks powerful operations when used in the right place.

😃 Thanks for reading!

Did you like the content? Found more content like this by joining to the Newsletter or following me on Twitter

📖 Keep reading