typeof (in types)

Gets the type of a variable or value so you can use it somewhere else.

On this page

Example

#
TypeScript
const defaultSettings = {
  theme: 'dark',
  fontSize: 16,
  sounds: true
}

type Settings = typeof defaultSettings
// type Settings = { theme: string; fontSize: number; sounds: boolean }

const custom: Settings = { ...defaultSettings, fontSize: 18 }
console.log(custom)
Result
{ theme: 'dark', fontSize: 18, sounds: true }

Definition and usage

#

In a type position, typeof returns the type of the given variable: type Config = typeof defaultConfig. That way you don’t have to describe by hand a type that already follows from an existing object.

It’s a different thing from the JavaScript typeof operator, which returns a string at runtime, such as "string". Both use the same word, but TypeScript tells them apart by context.

It’s often combined with keyof (keyof typeof COLORS) and as const to derive both values and types from a single object.

Syntax

#
Syntax
type Name = typeof variable

More examples

#
typeof at runtime
TypeScript
const level = 7
console.log(typeof level)
type Level = typeof level
// type Level = 7
Result
number

Good practices

#
  • When a configuration object is the source of truth, derive its type with typeof instead of writing it twice.
  • Combining typeof with as const keeps the literals instead of widening them to string.

Related entries

#

Spotted a mistake or missing an example? Write to us.