TypeScriptUnions and narrowing
typeof (in types)
Gets the type of a variable or value so you can use it somewhere else.
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 variableMore examples
#TypeScript
const level = 7
console.log(typeof level)
type Level = typeof level
// type Level = 7Result
number
Good practices
#- When a configuration object is the source of truth, derive its type with
typeofinstead of writing it twice. - Combining
typeofwithas constkeeps the literals instead of widening them tostring.
Related entries
#Spotted a mistake or missing an example? Write to us.