Mike Allanson

The typeof Type Operator

This is part 2 of my notes from working through the Beginner 1 exercise from TypeScript's Type | Treat 2021. Part 1 can be found here

typeof

TypeScript's typeof operator can be used in a type context to refer to the type of a variable or property. It's a complement to JavaScript's typeof operator, which works similarly but in an expression context.

Use typeof to refer to the type of the provided value.

Type Index Syntax

When using Indexed Access Types, there's a convenient helper for capturing the type of an array's elements. It looks something like typeof MyArray[number].

All Together

Putting all these features together gives us an approach to this problem. In short, the answer looks something like this:

const MyArray = ["a", "b", "c"] as const;
type Letter = typeof MyArray[number];
// ^? type Letter = "a" | "b" | "c"

Playground link