TypeScript's `typeof`: Get a Type from a Value
TypeScript's `typeof` operator grabs the static type from a runtime value, like a variable. It's essential for utilities like `ReturnType`, letting you derive a type from a function's implementation without duplicating definitions.
WHY IT EXISTS JavaScript has a typeof operator that returns a string for a value's type at runtime. TypeScript needed a parallel concept for its compile-time type system: a way to get the static type of a value without having to manually declare that type, keeping your code DRY (Don't Repeat Yourself).
THE MENTAL MODEL Think of TypeScript's typeof as a query to the compiler: "Look at this variable I've defined. What static type did you infer for it? Give me that type so I can use it in a type annotation." It lets your types follow your implementation, not the other way around.
HOW IT WORKS When used in a type context (e.g., let myVar: ...), typeof takes an identifier (a variable or property name) and resolves to its static type. For let s = "hello", the type typeof s is string. Its real power is with complex types. For a function f, ReturnType<typeof f> inspects the function's value and extracts its return type, saving you from writing it out by hand.
WHEN TO USE IT Use typeof to create types from existing values. This is common for capturing the type of a complex configuration object or deriving a function's signature to ensure type safety when passing it as a callback. It's a key tool for creating maintainable, inference-driven types.
WHEN NOT TO USE IT Do not confuse it with JavaScript's runtime typeof operator, which returns a string like "string" or "object". TypeScript's typeof is a compile-time operator. It is intentionally limited and cannot be used on complex expressions or function calls, like typeof myFunc(). This restriction prevents the confusing situation of writing code that looks like it executes but doesn't.
ONE CANONICAL EXAMPLE function getApiResponse() { return { status: 200, data: { user: "admin" } }; }
// We use typeof to get the type of the function value itself. // Then ReturnType extracts the type of what the function returns. type ApiResponse = ReturnType<typeof getApiResponse>;
// The 'ApiResponse' type is now correctly inferred as: // { status: number; data: { user: string; } } const response: ApiResponse = getApiResponse();
Read the original → typescriptlang.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.