Sub topic 3
Deriving a type from a value with typeof
This chapter assumes you can read TypeScript interfaces, type aliases, and union types, and that you are comfortable with JavaScript objects, arrays, and functions. You should also have met the idea of a generic type parameter. By the end, you will be able to turn an existing variable, property, class, or enum into a type, and know where that technique stops working.
Two meanings of typeof
JavaScript already has a typeof operator. It runs while your program executes and returns a string such as "object" or "number". TypeScript adds a second typeof that only exists in type positions. It never runs. The compiler reads it and substitutes the type it has inferred for the named value, and the compiler erases it from the emitted JavaScript.
The same word means different things depending on where it appears.
const point = { x: 10, y: 20 };
const runtimeKind = typeof point; // value position: the string "object" at runtime
type Point = typeof point; // type position: { x: number; y: number }
const other: Point = { x: 1, y: 2 };
console.log(runtimeKind, other);On the runtimeKind line, typeof point is an expression and evaluates to "object". On the type Point line, typeof point appears where a type is expected, so TypeScript treats it as a type query and asks what type point has.
The rule of thumb is to look at what is to the left. After type X =, after a : annotation, or inside <...> type arguments, you are in type space. Anywhere else, you are in value space.
Why derive a type from a value
Without typeof, you often write the same shape twice: once as an interface and once as a value that must match it. Two copies drift apart. When the value is the source of truth, deriving the type from it removes the second copy.
const defaultSettings = {
theme: "light",
fontSize: 14,
showSidebar: true,
};
type Settings = typeof defaultSettings;
function applySettings(overrides: Partial<Settings>): Settings {
return { ...defaultSettings, ...overrides };
}
applySettings({ fontSize: 16 });
// applySettings({ fontSize: "large" }); // Error: string is not assignable to numberIf you later add language: "en" to defaultSettings, Settings and applySettings pick it up without further edits.
Choose the direction by asking which side should be authoritative. If the type is a contract that many values must satisfy, such as an API response, write the interface and annotate the values. If one concrete value defines the shape, such as a configuration object, derive the type from it.
What type you actually get
typeof reports the type the compiler inferred for the value, and inference follows widening rules. These rules decide whether you get a precise type or a general one.
const direction = "north";
let heading = "north";
const flags = { verbose: true };
type A = typeof direction; // "north"
type B = typeof heading; // string
type C = typeof flags; // { verbose: boolean }- A
constprimitive keeps its literal type, because it can never change.directionis"north". - A
letvariable is widened to the general type, because it may be reassigned.headingisstring. - Properties of an object literal are widened even when the object is declared with
const. Declaring the objectconststops reassignment of the variable, not mutation of its properties.verboseis thereforeboolean, nottrue.
Object properties are the usual surprise. If you want theme to be the literal "light" rather than string, you must ask for it explicitly. The as const assertion does that, and a later chapter covers it.
An explicit annotation overrides inference, and typeof reports the annotation.
interface Settings {
theme: "light" | "dark";
fontSize: number;
}
const current: Settings = { theme: "light", fontSize: 14 };
type Current = typeof current; // Settings, not { theme: "light"; fontSize: number }Here typeof current gives you Settings back. Deriving a type from an annotated variable is legal but adds nothing, since you could have written Settings directly.
Reaching into nested values
A type query accepts a variable name or a dotted path of property accesses starting from a variable. That lets you pull out a sub-part of a larger value.
const server = {
network: { host: "localhost", port: 8080 },
tags: ["web", "internal"],
};
type Network = typeof server.network; // { host: string; port: number }
type Tags = typeof server.tags; // string[]
const backup: Network = { host: "10.0.0.2", port: 9090 };
console.log(backup);Only identifiers and dotted property names are allowed after typeof. Bracket access such as typeof server["network"] is not valid syntax in a type query. To look up properties by key, combine typeof with an indexed access type, (typeof server)["network"]. Indexed access types are the topic of a later chapter.
Classes, enums, and the constructor trap
A class name lives in both spaces. In a type position, Logger means the type of an instance. In a value position, Logger is the constructor function. typeof Logger in a type position gives you the type of that constructor, which is a different thing from the instance type.
class Logger {
constructor(public prefix: string) {}
log(message: string): void {
console.log(`${this.prefix}${message}`);
}
}
type LoggerInstance = Logger; // has prefix and log
type LoggerConstructor = typeof Logger; // new (prefix: string) => Logger, plus statics
function build(ctor: LoggerConstructor, prefix: string): Logger {
return new ctor(prefix);
}
build(Logger, "[app] ").log("started");A parameter typed LoggerConstructor accepts the class itself, not an instance of it. Typing it as Logger is a common mistake, and the compiler will then reject Logger being passed in.
Enums behave the same way. An enum name is a value, an object holding the members, and also a type, the union of its members.
enum Color {
Red,
Green,
}
type ColorMember = Color; // Color.Red | Color.Green
type ColorObject = typeof Color; // { Red: Color.Red; Green: Color.Green; ... }Use the plain name when you mean one member of the enum. Use typeof Color when you mean the lookup object itself.
What typeof cannot do
A type query accepts only a reference to something that exists as a value. It does not evaluate expressions. Three failures account for most of the errors you will see.
interface Point {
x: number;
y: number;
}
function createUser(name: string) {
return { id: 1, name };
}
// type Bad1 = typeof Point;
// Error: 'Point' only refers to a type, but is being used as a value here.
// type Bad2 = typeof createUser("Ada");
// Error: call expressions are not allowed in a type query.
// type Bad3 = typeof 42;
// Error: a type query needs an identifier, not a literal.
type CreateUserFn = typeof createUser; // (name: string) => { id: number; name: string }The table below summarizes the cases.
| Written after `typeof` | Allowed | Why |
|---|---|---|
| A variable such as `config` | Yes | It is a value with an inferred type |
| A dotted path such as `server.network` | Yes | Property access on a value |
| A function name such as `createUser` | Yes | Gives the function's type, not its result |
| A class or enum name | Yes | Gives the constructor type or enum object type |
| An interface or type alias | No | These exist only in type space |
| A call such as `createUser("Ada")` | No | Type queries do not run or evaluate expressions |
| A literal such as `42` | No | Not a reference to a declared value |
To get a function's result type without calling it, apply typeof to the function name and pass that to a utility type. A later chapter covers ReturnType and Parameters.
Errors and gotchas
- Using the type name where a value is needed.
typeof Pointfails whenPointis an interface. Removetypeofand usePointdirectly. - Expecting literals from object properties.
typeof configgives{ theme: string }, not{ theme: "light" }. Addas const, or annotate with a union type, when you need the narrower type. - Forgetting that
letwidens.typeof headingisstringwhen declared withlet, even if the initial value was a literal. - Confusing instance and constructor types. Use
Loggerfor an instance andtypeof Loggerfor the class itself. - Assuming the type updates the value. The type is a snapshot of what the compiler inferred. It does not enforce anything on the value beyond what the compiler already checks, and it adds no runtime check.
- Mixing up the two typeofs in one expression.
typeof x === "string"is the runtime operator, used for narrowing.type T = typeof xis the type query. Both are legal in the same file, and the position decides which one you have.
Exercises
Exercise
Given const retries = 3; let timeout = 3000; const options = { retries, verbose: false };, what are typeof retries, typeof timeout, and typeof options when used in type positions?
Show answer
typeof retries is the literal type 3, because a const primitive keeps its literal type. typeof timeout is number, because let widens. typeof options is { retries: number; verbose: boolean }. The properties of an object literal are widened even though the object is declared with const.
Exercise
A function must accept the class Logger itself, so it can call new on it, rather than an instance. Which parameter type is correct, Logger or typeof Logger, and why?
Show answer
typeof Logger. In a type position Logger means the instance type. typeof Logger is the type of the constructor value, which includes the new signature and any static members. A parameter typed Logger would accept an instance and would not allow new ctor(...).
Exercise
Why does type T = typeof createUser("Ada"); fail, and how do you describe the type of the function itself instead?
Show answer
A type query only accepts an identifier or a dotted path of identifiers. It does not evaluate call expressions. Write typeof createUser to get the function's type. If you need the type of its result, pass that to the ReturnType utility type.