- Abstract class
- Annotations
- Array
- Asserts
- Casting
- Class
- Comments
- Conditional types
- Const
- Data types
- Date object
- Decorators
- Default parameter
- Dictionary
- Enum
- Exclude type
- Extract type
- For loop
- forEach()
- Function
- Generic types
- Generics
- Index signature
- Infer
- Inheritance
- Interface
- Intersection types
- Keyof type operator
- Let
- Map type
- Mixin
- Module
- Namespace
- Never
- Object type
- Omit type
- Operator
- Optional parameter
- Partial type
- Pick type
- Promise
- Property
- Readonly type
- Record type
- Required type
- Satisfies operator
- Tuples
- Type alias
- Type assertion
- Type guard
- Type narrowing
- Typeof Type Operator
- Union
- Utility types
- Var
- Void
TYPESCRIPT
TypeScript typeof Type Operator: Syntax, Use Cases, and Examples
The typeof operator in TypeScript lets you extract the type of a variable or value and reuse it throughout your code. It's a compile-time tool that enables dynamic type inference based on existing values, which helps prevent duplication and ensures consistency.
This operator shines when you're working with config objects, constant values, shared utilities, or dynamic return types. It helps you mirror the shape of a value into a type—without writing the same structure twice.
What Is the typeof Type Operator?
In TypeScript, typeof is used to get the type of a variable or value. Unlike the JavaScript typeof, which evaluates the value at runtime, TypeScript’s version extracts the type at compile time.
Example
const user = {
name: "Alice",
age: 30,
};
type UserType = typeof user;
UserType now refers to the type { name: string; age: number }.
Basic Syntax of typeof in TypeScript
The syntax is straightforward:
type NewType = typeof existingVariable;
You must define the variable before using typeof to extract its type.
Using typeof with Constants
You can use typeof to mirror the structure of constant objects or configuration values.
const config = {
baseURL: "https://api.example.com",
timeout: 5000,
};
type ConfigType = typeof config;
This ensures other parts of your application use the exact same structure.
Using typeof with Arrays
You can extract both the array shape and item types with typeof.
const colors = ["red", "green", "blue"];
// Entire array type
type ColorArray = typeof colors; // string[]
// Union of item values
type ColorItem = typeof colors[number]; // "red" | "green" | "blue"
This is useful when turning static arrays into type-safe dropdown values or filters.
Using typeof with Functions
You can use typeof to extract a function’s signature and reuse it elsewhere.
function greet(name: string): string {
return `Hello, ${name}`;
}
type GreetFn = typeof greet;
const sayHi: GreetFn = (name) => `Hi, ${name}`;
This pattern supports type-safe callbacks, wrappers, or higher-order functions.
Combining typeof and keyof
When paired with keyof, typeof helps you create key unions from runtime objects.
const status = {
success: "SUCCESS",
error: "ERROR",
pending: "PENDING",
};
type StatusKey = keyof typeof status; // "success" | "error" | "pending"
type StatusValue = typeof status[StatusKey]; // "SUCCESS" | "ERROR" | "PENDING"
This is useful when you want to restrict access to only known object keys or values.
Runtime Type Checks with typeof
The JavaScript typeof still works in TypeScript to check a variable’s type at runtime.
function checkType(val: unknown) {
if (typeof val === "string") {
console.log("It's a string!");
}
}
Use it to narrow unknown or union types in functions that deal with dynamic values.
Type Narrowing with Switch and typeof
In more complex type unions, a switch statement with typeof can be used to safely branch logic.
function printValue(value: string | number | boolean) {
switch (typeof value) {
case "string":
console.log(value.toUpperCase());
break;
case "number":
console.log(value.toFixed(2));
break;
case "boolean":
console.log(value ? "Yes" : "No");
break;
}
}
TypeScript narrows the variable type within each case branch based on the condition.
Inferring Complex Types from Nested Constants
typeof is a powerful way to mirror deep object structures into reusable types.
const Theme = {
colors: {
primary: "#000",
secondary: "#FFF",
},
spacing: {
small: 4,
large: 16,
},
};
type ThemeType = typeof Theme;
type ColorKeys = keyof typeof Theme.colors; // "primary" | "secondary"
Use this when building themes, design systems, or nested config objects.
Getting Return Types with typeof
You can combine typeof and ReturnType to infer the output of a function.
function getUser() {
return {
id: 1,
name: "Jane",
};
}
type User = ReturnType<typeof getUser>; // { id: number; name: string }
This makes sure that other functions or components using the result always match the return shape.
Defining Literal Union Types from Constants
Use as const with typeof to extract literal value types from an object.
const Role = {
ADMIN: "admin",
USER: "user",
} as const;
type RoleType = typeof Role[keyof typeof Role]; // "admin" | "user"
This pattern is common in form validation, dropdown fields, and access control.
Building Generic Utilities with typeof
In dynamic systems, typeof helps you enforce consistency across action maps or plugins.
const actions = {
add: (a: number, b: number) => a + b,
subtract: (a: number, b: number) => a - b,
};
type ActionKeys = keyof typeof actions;
type ActionFn = typeof actions[ActionKeys];
You can now safely reference add and subtract without redefining their type each time.
Limitations of the typeof Operator
While useful, typeof in TypeScript has a few restrictions:
- It only works on identifiers, not expressions like
typeof (a + b) - It doesn’t evaluate values—it only reflects the shape of the declared value
- It can’t be used with runtime results unless you capture them first in a variable
To enhance precision, pair it with as const, keyof, ReturnType, or Parameters for richer type inference.
Summary
The typeof operator in TypeScript helps you extract static types from runtime values and reuse them safely across your codebase. It simplifies type creation, improves consistency, and reduces boilerplate in large-scale applications.
Use typeof to infer types from constants, arrays, functions, or complex nested structures. Combined with tools like keyof and as const, it’s one of the most flexible and practical tools for type-safe development in TypeScript.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.