Configuration contracts
Derive a reusable configuration type directly from a typed configuration value.
TypeScript · Const
In a type context, TypeScript’s typeof operator obtains the static type of a variable or property. It is especially useful for deriving reusable types from values and composing with utilities such as ReturnType.
In a type position, typeof obtains the static type of an identifier or one of its properties. It is useful for reusing inferred object or function types and can be combined with operators such as ReturnType; it is distinct from JavaScript's runtime typeof expression.
typeof identifier
typeof identifier.propertyThe static type of the referenced identifier or property.
typeof after a type operator or annotation to reuse the static type of a named value or property.typeof, enabling utilities such as ReturnType.typeof cannot be applied to arbitrary expressions; use an identifier or its property.typeof when converting a value reference into a type.const settings = {
retries: 3,
endpoint: "/api",
};
type Settings = typeof settings;
function load(config: Settings): string {
return `${config.endpoint} (retries: ${config.retries})`;
}
console.log(load(settings));The type is derived from the value, so the function accepts objects matching the inferred shape.
Derive a reusable configuration type directly from a typed configuration value.
Pass a function's exact type to a utility or derive its return type without repeating its signature.
Capture the shape of an object or element type from an array value.
typeof mean in a TypeScript type position?In a type position, typeof value produces the static type inferred for that value. Unlike JavaScript's runtime operator, it lets a type refer to a variable or property type.
Follow-up: Can it inspect an arbitrary expression? No; bind the expression to an identifier or access a property before applying the type operator.
typeof useful in a large codebase?It is useful when a value is the source of truth for a type, especially for object literals, configuration values, and function values. The resulting type tracks the value's inferred shape.
Follow-up: How can you derive a function's return type? Use ReturnType<typeof functionName>, which combines typeof with the utility type.
typeof compose with other type operators?typeof can be combined with other type operators to express patterns such as ReturnType<typeof f>. It can also capture an array value's element type with an indexed access such as typeof items[number].
Follow-up: What restriction applies to the operand? Only identifiers and their properties are permitted, not arbitrary expressions.
ReturnTypekeyofIndexed Access TypesCreating Types from Types