Sub topic 3
Deriving a Type from a Value with `typeof`
This chapter assumes you know interfaces, type aliases, union types, JavaScript objects and functions, and basic generics.
TypeScript has two related meanings for typeof:
- In JavaScript expressions,
typeof valueruns at runtime and returns a string such as"string"or"object". - In a TypeScript type position,
typeof valuereads the static type that TypeScript already inferred for a value.
The second meaning lets you derive a type from an existing variable or function.
`typeof` in a type position
Consider this configuration object:
const config = {
host: "localhost",
port: 8080,
};
type Config = typeof config;
function connect(options: Config): string {
return `Connecting to ${options.host}:${options.port}`;
}
console.log(connect(config));TypeScript infers Config from the value assigned to config. In this example, Config is equivalent to:
type Config = {
host: string;
port: number;
};The value config exists at runtime. The type alias Config exists only during type checking. TypeScript removes the alias when it emits JavaScript.
This approach avoids describing the same object shape twice. If you add a property to config, Config changes automatically.
Runtime `typeof` and type-level `typeof`
The position of the operator determines its meaning:
const port = 8080;
const runtimeKind = typeof port;
// Runtime value: "number"
type Port = typeof port;
// Type: numberruntimeKind is a JavaScript value. The expression runs when the program runs.
Port is a TypeScript type. It disappears after compilation.
TypeScript's type-level form accepts a value name or a property access. It does not evaluate an arbitrary expression as a type.
const settings = {
retries: 3,
};
type Settings = typeof settings;
type RetryCount = typeof settings.retries;Here, Settings is the object type and RetryCount is number.
Deriving types from functions
Functions are values, so typeof can capture a function's complete type. This is useful with utility types such as ReturnType and Parameters.
function createUser(name: string, active: boolean) {
return {
id: 1,
name,
active,
};
}
type CreateUser = typeof createUser;
type NewUser = ReturnType<typeof createUser>;
type CreateUserArguments = Parameters<typeof createUser>;
const user: NewUser = createUser("Ada", true);
const argumentsForCreateUser: CreateUserArguments = ["Grace", false];
console.log(user, argumentsForCreateUser);CreateUser describes the function itself:
type CreateUser = (name: string, active: boolean) => {
id: number;
name: string;
active: boolean;
};NewUser describes the returned object. CreateUserArguments is a tuple containing the parameter types in order.
The function name is important in ReturnType<typeof createUser>. ReturnType<createUser> is invalid because createUser is a value, not a type. The type query typeof createUser converts the function value into a function type that the utility can use.
Inference and literal precision
A derived type reflects the type inferred for the value. It does not necessarily preserve every literal spelling.
const mode = "development";
type Mode = typeof mode;
// Type: stringBecause mode is a mutable variable, TypeScript widens its type to string. If you need the exact literal type, use a const assertion:
const exactMode = "development" as const;
type ExactMode = typeof exactMode;
// Type: "development"The same idea applies to object properties and arrays. Literal preservation with as const is especially useful when building a union from a list of allowed values.
A mental model
Use type-level typeof when a value should be the source of truth for a type. Use a separately written interface when the type must describe data before a particular value exists, or when you want a public contract independent of one implementation.
Exercise
What are the types of RuntimeKind and User in this code?
const value = 42;
const makeUser = (name: string) => ({ name, id: 1 });
const RuntimeKind = typeof value;
type User = ReturnType<typeof makeUser>;
Show answer
RuntimeKind is a runtime variable with the value "number", not a type alias. User is the object type { name: string; id: number }.