Harnessing The Power Of The keyof Operator
Published: Jun 21, 2023
Last updated: Jun 21, 2023
This post will is 7 of 20 for my series on intermediate-to-advance TypeScript tips.
All tips can be run on the TypeScript Playground.
Introduction
In TypeScript, the keyof operator is a powerful tool that can be used to extract the keys of a given type. The operator takes an object type and produces a string or numeric literal union of its keys. This feature becomes especially useful when combined with mapped types. For a more detailed explanation, you can refer to the official TypeScript documentation here.
Practical Example 1: Basic Usage of keyof
Let's start with a simple example. Suppose we have a Point type defined as follows:
type Point = { x: number; y: number };
We can use the keyof operator to get the keys of the Point type:
type P = keyof Point; // P is now "x" | "y"
In this case, P is a type that represents either "x" or "y", which are the keys of the Point type.
Practical Example 2: keyof with Index Signatures
The keyof operator also works with index signatures. Consider the following example:
type Arrayish = { [n: number]: unknown }; type A = keyof Arrayish; // A is now number
Here, A is a type that represents a number, which corresponds to the numeric index signature of the Arrayish type.
Practical Example 3: keyof with String Index Signatures
When the type has a string index signature, keyof will return a union of string and number. This is because JavaScript object keys are always coerced to a string. Here's an example:
type Mapish = { [k: string]: boolean }; type M = keyof Mapish; // M is now string | number
In this case, M is a type that represents either a string or a number, which corresponds to the string index signature of the Mapish type.
Summary
The keyof operator in TypeScript is a powerful tool that allows us to extract the keys of a given type. It works with both regular object types and types with index signatures. By understanding and harnessing the power of the keyof operator, we can write more flexible and robust TypeScript code.
All code snippets above are available here on the TypeScript playground.
References
Photo credit: jannerboy62
Harnessing The Power Of The keyof Operator
Introduction