`typeof` (Type-Level)

Get the Type of a Value

`typeof` (Type-Level)

In a type position, `typeof value` evaluates to the value's type. Different from the runtime `typeof` operator.

3 min read Level 2/5 #typescript#typeof#advanced
What you'll learn
  • Recognize type-position `typeof`
  • Tell it from the runtime operator
  • Use it for "match this value's shape"

TypeScript has two typeofs:

  • Runtimetypeof x === "string" (JavaScript)
  • Type-leveltype X = typeof someValue (TypeScript)

The type-level one extracts a value’s TYPE so you can use it elsewhere.

Capture a Variable’s Type

const user = { name: "Ada", age: 36 };

type User = typeof user;
// { name: string; age: number }

Useful when you write a value first and want the type to follow the value.

With Literal Types (Use as const)

const roles = ["admin", "user", "guest"] as const;
type Role = typeof roles[number];   // "admin" | "user" | "guest"

Without as const, roles would be string[] and Role would be string — much less useful.

Function Types

function fetchUser(id: string): Promise<User> { /* ... */ }

type FetchUserFn = typeof fetchUser;
// (id: string) => Promise<User>

Capture a function’s signature without retyping it.

ReturnType Pattern

type User = ReturnType<typeof fetchUser>;
//     ^ Promise<User>

ReturnType<T> is a built-in utility. Combine with typeof to ask “what does this function return?”. A common idiom.

When to Reach For It

  • A const config value should drive a type
  • You want the type from a function or module without re-typing
  • Capturing literal types from a value (with as const)

Common Mistake

const obj = { name: "Ada" };

type T = typeof obj.name;
//      ^ string

typeof obj.name gives you string, NOT "Ada"obj isn’t as const. Add as const to keep the literal.

Up Next

T[K] — indexed access into a type.

Indexed Access →