- Abstract class
- Annotations
- Array
- Asserts
- Casting
- Class
- Conditional types
- Const
- Date object
- Decorators
- Default parameter
- Dictionary
- Enum
- Exclude type
- Extract type
- For loop
- forEach()
- Function
- Generics
- Index signature
- Infer
- Inheritance
- Interface
- 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 TypeScript typeof
type operator allows you to extract the type of a variable or value and use it elsewhere in your code. By using typeof TypeScript
, you can create types dynamically from existing variables, functions, or even complex object structures without repeating yourself.
This operator is crucial when working with constant objects, third-party libraries, or dynamically typed values. It enhances type safety and reduces boilerplate, making code more maintainable and less error-prone.
In this guide, you'll learn how the typeof
operator works in TypeScript, how to combine it with other tools like keyof
, how to use it with arrays and functions, and how it interacts with runtime typeof
checks.
What Is the TypeScript typeof
Type Operator?
In TypeScript, the typeof
type operator gets the type of a variable or value at compile time. It’s different from the typeof
operator in JavaScript, which evaluates types at runtime.
Example:
const user = {
name: "Alice",
age: 30,
};
type UserType = typeof user;
Here, UserType
is inferred as the structure of the user
object. You can now reuse this type without having to manually declare an interface.
Syntax of typeof
in TypeScript
The syntax is straightforward:
type NewType = typeof existingVariable;
The variable must already exist in the scope before you apply typeof
.
Using TypeScript typeof
with Constants
When working with constants like configuration objects or enums, you can use typeof
to reflect their type.
const config = {
baseURL: "https://api.example.com",
timeout: 5000,
};
type ConfigType = typeof config;
Now ConfigType
can be used to annotate other functions or enforce structure consistency.
TypeScript typeof
and Arrays
The typescript typeof array
pattern lets you infer the type of array elements and reuse them.
const colors = ["red", "green", "blue"];
type Colors = typeof colors[number]; // "red" | "green" | "blue"
This technique helps define value-based union types from array contents, often useful in dropdowns or filters.
You can also define array shapes with:
type ColorArray = typeof colors; // string[]
TypeScript typeof
with Functions
You can extract a function’s signature using typeof
and reuse it for function parameters or callbacks.
function greet(name: string): string {
return `Hello, ${name}`;
}
type GreetType = typeof greet; // (name: string) => string
const sayHello: GreetType = (name) => `Hi, ${name}`;
This enables strong typing across shared handlers or modules.
Combining typeof
and keyof
When you combine TypeScript keyof typeof
, you create a type that consists of all the keys of a given value.
const status = {
success: "SUCCESS",
error: "ERROR",
pending: "PENDING",
};
type StatusKeys = keyof typeof status; // "success" | "error" | "pending"
type StatusValues = typeof status[StatusKeys]; // "SUCCESS" | "ERROR" | "PENDING"
This is a powerful pattern for dynamic value types derived from objects or config files.
Checking typeof
in TypeScript at Runtime
TypeScript compiles to JavaScript, so you can still use the regular runtime typeof
operator to check the type of a value.
function checkType(val: unknown) {
if (typeof val === "string") {
console.log("It's a string!");
}
}
This check typeof TypeScript
technique is useful when narrowing unknown types to concrete ones.
Switch typeof
TypeScript Pattern
In situations with multiple possible types, you can use a switch typeof TypeScript
structure to refine the value:
function logValue(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 will automatically infer and narrow the type based on the branch.
Inferring Complex Types Using typeof
When working with structured constants, typeof
saves you from manually creating interfaces or repeating code.
const Theme = {
colors: {
primary: "#000",
secondary: "#FFF",
},
spacing: {
small: 4,
large: 16,
},
};
type ThemeType = typeof Theme;
type ColorKeys = keyof typeof Theme.colors; // "primary" | "secondary"
You can now pass ThemeType
to components, maintain consistency, and evolve types with minimal effort.
Dynamic Return Types with typeof
You can also extract return types from function instances using a combination of typeof
and ReturnType
.
function getUser() {
return {
id: 1,
name: "Jane",
};
}
type User = ReturnType<typeof getUser>; // { id: number; name: string }
This ensures return type consistency when working with API utilities or data-fetching functions.
typeof
with Enums and Literal Types
When using enums or constant objects, you can use typeof
to build value types dynamically.
const Role = {
ADMIN: "admin",
USER: "user",
} as const;
type RoleType = typeof Role[keyof typeof Role]; // "admin" | "user"
This technique is popular for defining value constraints in forms, dropdowns, or conditional rendering logic.
Creating Generic Utilities with typeof
With typeof
, you can craft utilities that work across different datasets or modules.
const actions = {
add: (a: number, b: number) => a + b,
subtract: (a: number, b: number) => a - b,
};
type ActionKeys = keyof typeof actions;
type ActionFunction = typeof actions[ActionKeys]; // (a: number, b: number) => number
This pattern is helpful in plugin systems, reducers, or command pattern implementations.
Limitations of typeof TypeScript
While powerful, the typeof
operator has some limitations:
- It works only with identifiers (you cannot use it directly on expressions like
typeof (a + b)
) - It reflects the shape, not the runtime value or instance
- It cannot infer types from runtime-only data
To get around these, use as const
for literal inference and ReturnType
or Parameters
when working with functions.
Summary
The TypeScript typeof
type operator gives you the ability to extract types from values and reuse them throughout your application. You can apply it to constants, objects, arrays, functions, and enums to reduce redundancy and enforce type safety.
Combining typeof TypeScript
with keyof
, as const
, and other utility types creates expressive, scalable code. You can build types from live values, avoid duplication, and craft reusable components and utilities with confidence.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.