TypeScript has the keyof
and typeof
keywords allowing you to retrieve related keys and types of a value or type. We used the combination keyof typeof
in tutorials here on Future Studio showing you how to get all enum keys and how to use a string as enum key.
This tutorial takes a closer look at how these keywords work.
TypeScript Series Overview
- How to Export Transpiled Code From package.json
- Use Nodemon to Restart Your Server on Changes
- How to Allow Trailing Commas (Comma-Dangle) With Typescript-ESLint
- Use SWC to Speed up TypeScript Code
- Fixing Null Type Ignored in Union Type
- How to Remove Index Signature from a Type
- Module Augmentation Overwrites Declarations Instead of Merging Them
- Get All Keys of an Enum
- Get All Values of an Enum
- Using a String as Enum Key
- Understanding “keyof typeof”
- Get Type of Class Properties and Omit Methods
The keyof typeof
Keywords in TypeScript
Let’s recap the sample code from the tutorial on how to get all enum keys in TypeScript. We have an enum for the Future Studio books mapping a slug to their titles. You can retrieve a union type of all enum keys using keyof typeof
:
export enum FutureStudioBooks {
retrofit = 'Retrofit Book',
picasso = 'Picasso Book',
glide = 'Glide Book',
gson = 'Gson Book',
'gson-workbook' = 'Gson Workbook',
}
type FutureStudioBooksKey = keyof typeof FutureStudioBooks
// type FutureStudioBooksKey = "retrofit" | "picasso" | "glide" | "gson" | "gson-workbook"
Enums in TypeScript are similar to objects with strictly typed keys and values. Let’s look at an object concerning the keyof
and typeof
keywords.
We’re keeping the book example and creating a basic Retrofit book object. You can use typeof
to create a type for the shape of an input object:
const book = {
slug: 'retrofit',
title: 'Retrofit Book',
price: 28
}
type Book = typeof book
// type Book = {
// slug: string;
// title: string;
// price: number;
// }
Now you have the type of a book object. You can now use keyof
on that book object type to create a union type of all keys:
type BookProps = keyof Book;
// type BookProps = "slug" | "title" | "price"
The combination keyof typeof
on an object creates a union of literal types of all fields in the object:
const book = {
slug: 'retrofit',
title: 'Retrofit Book',
price: 28
}
type BookProps = keyof typeof book;
// type BookProps = "slug" | "title" | "price"
As you can see, keyof typeof
works the same way on enums and objects in TypeScript.
Enjoy!
Mentioned Resources
- how to get all
enum
keys in TypeScript tutorial here on Future Studio - how to use a string as an
enum
key in TypeScript tutorial here on Future Studio