Introduction to typeof in TypeScript
The typeof operator is useful when working with values and types in TypeScript. It lets you inspect the type of a value at runtime and, in a type position, reuse the type that TypeScript has inferred for an existing variable or property.
This becomes especially helpful when an application contains configuration objects, API response models, shared constants, or functions whose types should stay synchronized with existing implementations.
TypeScript supports two closely related forms: the JavaScript typeof operator, which returns a string while the program runs, and the TypeScript typeof type operator, which obtains a type during compilation.
1. JavaScript typeof at Runtime
JavaScript includes typeof for checking the runtime type category of a value. TypeScript supports this operator because TypeScript code ultimately runs as JavaScript after compilation or transformation.
const username = "Abhinash";
const age = 27;
const isDeveloper = true;
console.log(typeof username); // "string"
console.log(typeof age); // "number"
console.log(typeof isDeveloper); // "boolean"
The runtime operator returns a string such as "string", "number", or "boolean". It does not return TypeScript types such as string or number.
Remember that JavaScript's runtime behavior has some historical quirks. For example, typeof null returns "object", and arrays also return "object". Use Array.isArray() to identify arrays reliably.
2. The typeof Type Operator
In a TypeScript type declaration, typeof allows you to derive a type from an existing value. This is also called a type query.
const username = "Abhinash";
const score = 95;
type UsernameType = typeof username;
type ScoreType = typeof score;
Because both variables use const with primitive initializers, TypeScript infers the literal types "Abhinash" and 95 for these type queries. The result is more specific than simply string or number.
Compare that with a variable declared using let:
let currentStatus = "active";
type CurrentStatus = typeof currentStatus;
// CurrentStatus is string
Since a let variable can be reassigned, TypeScript generally infers a broader type for a primitive value. Using typeof in a type declaration preserves the type inferred for that variable rather than automatically converting every value into a literal type.
3. Deriving Object Types
One of the most useful applications of typeof is deriving a type from an existing object. Instead of writing the same structure twice, define the object and let TypeScript infer its type.
const user = {
id: 101,
name: "Abhinash",
isActive: true
};
type User = typeof user;
const anotherUser: User = {
id: 102,
name: "Ravi",
isActive: false
};
In this example, User is derived from the shape of user. Its properties are inferred as number, string, and boolean. Object properties are generally widened to these types unless a more specific annotation or const assertion is used.
If the original object's structure changes, the derived type reflects those changes automatically. This reduces duplication and helps prevent the value and its corresponding type from drifting apart.
4. Using typeof with as const
Sometimes you need to preserve exact string or numeric values rather than infer broader types. The as const assertion is useful for this purpose.
const appConfig = {
environment: "production",
retries: 3
} as const;
type AppConfig = typeof appConfig;
// environment: "production"
// retries: 3
Here, the inferred property types are the literal types "production" and 3. The properties are also readonly at the type level.
This is useful for configuration constants and fixed application settings. However, as const is a compile-time type assertion, not a runtime deep-freeze operation.
5. Creating Types from Constant Values
You can combine typeof with indexed access types to create a union from the values of an object or array. This is useful for statuses, permission names, navigation keys, and other predefined options.
const statuses = {
pending: "pending",
approved: "approved",
rejected: "rejected"
} as const;
type Status = (typeof statuses)[keyof typeof statuses];
// Status is:
// "pending" | "approved" | "rejected"
The expression typeof statuses obtains the object's type. The keyof operator obtains its keys, and the indexed access expression extracts the types of the corresponding values.
The same technique works with arrays:
const roles = ["admin", "editor", "viewer"] as const;
type Role = (typeof roles)[number];
// Role is:
// "admin" | "editor" | "viewer"
In the array example, number is used as the index type to obtain the union of the tuple's element types. The as const assertion preserves the individual values instead of widening them to a general string array.
6. Using typeof with Functions
The type query works with functions, too. You can obtain a function's complete type from its existing declaration, then use utility types such as ReturnType to inspect specific parts of that type.
function createUser(name: string, age: number) {
return {
name,
age,
createdAt: new Date()
};
}
type CreateUserFunction = typeof createUser;
type CreatedUser = ReturnType<typeof createUser>;
const createUserCopy: CreateUserFunction = createUser;
CreateUserFunction describes the function's parameter and return types. CreatedUser represents the inferred return type of the function.
This approach is especially helpful when several functions, services, or modules need to share a consistent type without manually repeating the complete structure.
7. typeof with Class and Imported Values
When used in a type position, typeof can also describe the static side of a class, including its constructor and static members.
class Account {
constructor(public id: number) {}
}
type AccountConstructor = typeof Account;
const AccountReference: AccountConstructor = Account;
const account = new AccountReference(101);
The type Account normally describes an instance of the class, whereas typeof Account describes the class value itself, including how it can be constructed. This distinction matters when passing classes into factories or APIs that create instances.
You can also use a type query with an imported value when you need to reuse its existing type. Make sure the value is imported correctly and is available under the module's export structure.
8. Runtime typeof vs. TypeScript typeof
| Feature | Runtime typeof | Type-query typeof |
|---|---|---|
| Purpose | Checks a value's runtime category | Derives a type from a value |
| Example | typeof age |
type Age = typeof age |
| Result | A string at runtime | A TypeScript type |
| Where used | Executable expressions | Type declarations |
The type-query form is handled by the TypeScript compiler. Type annotations and type declarations are erased from the emitted JavaScript, so a declaration such as type User = typeof user does not create a runtime variable or perform a runtime check.
9. Common Mistakes to Avoid
-
Confusing a runtime result with a type:
typeof valuereturns a JavaScript string in an expression, whiletype Value = typeof valuedefines a TypeScript type. -
Expecting every const property to become a literal: primitive variables declared with
constoften retain literal types, but object properties generally widen withoutas const. -
Using typeof as complete runtime validation: checking
typeof data === "object"does not validate an API response's properties or distinguish all object-like values. - Trying to obtain a type from a type name: type queries operate on values. To derive a type from an existing value, refer to that value in the type query.
- Repeating types unnecessarily: when a value already defines the intended structure, deriving the type can avoid maintaining duplicate declarations.
10. Best Practices for typeof
- Use type queries to keep related value and type declarations synchronized.
- Use
as constwhen fixed object or array values should produce literal types. - Combine
typeof,keyof, and indexed access types when deriving unions from constant objects and tuples. - Use
ReturnType<typeof functionName>when you need the return type of an existing function. - Keep runtime validation separate from compile-time typing, especially when handling external data such as API responses.
Conclusion
TypeScript's typeof connects existing values with their inferred types. Its runtime form supports basic value-category checks, while its type-query form helps define reusable types for objects, functions, class constructors, and constant values.
Once you understand the difference between these two forms, you can reduce duplicated type declarations, preserve useful literal types, and build code that stays consistent as your application evolves.