🧠 TypeScript β€” typeof Type Operator: Explained with Examples

🧲 Introduction – Understanding typeof in TypeScript

In TypeScript, the typeof operator is more than just a runtime tool β€” it can also be used in type positions to infer or reference the type of a value. This enables strong typing based on existing variables or constants, ensuring type safety without code duplication.

🎯 In this guide, you’ll learn:

  • What the typeof operator does in a type context
  • Difference between JavaScript typeof and TypeScript typeof
  • Use cases with variables, functions, arrays, and type aliases
  • How typeof works with keyof and indexed types

πŸ“˜ What Is typeof in TypeScript?

In JavaScript, typeof is used at runtime to check the type of a value.

console.log(typeof "hello"); // "string"

In TypeScript, typeof is also used at compile time to get the type of a variable, constant, or function β€” not just its runtime type.

let user = { name: "Alice", age: 30 };
type User = typeof user;
// Equivalent to: { name: string; age: number }

🧱 Basic Syntax of typeof Type Operator

type NewType = typeof someVariable;

This copies the type definition from the variable into the type NewType.


πŸ” Examples: typeof in Action

πŸ§ͺ Example 1: Typing Based on Variable

const point = { x: 10, y: 20 };
type Point = typeof point;
// Point is now: { x: number; y: number }

πŸ§ͺ Example 2: Use with Functions

function greet(name: string) {
  return `Hello, ${name}`;
}

type GreetFn = typeof greet;
// GreetFn is (name: string) => string

πŸ§ͺ Example 3: typeof with Arrays

const roles = ["admin", "user", "guest"] as const;
type Role = typeof roles[number];
// Role = "admin" | "user" | "guest"

πŸ” typeof + keyof: Dynamic Type Utilities

const settings = {
  theme: "dark",
  notifications: true,
};

type Settings = typeof settings;
type SettingsKeys = keyof typeof settings;
// "theme" | "notifications"

This combo allows powerful manipulation of types at scale.


πŸ› οΈ Practical Use Cases

Use CaseHow typeof Helps
πŸ“„ Create type from an existing objectAvoids duplication
βš™οΈ Type safe function referencesExtract function type signatures
πŸ”„ Use dynamic keyof and indexed accessWorks with mapped/utility types
🧰 Works with ReturnType, Parameters, etc.Improves reusability and inference

🚫 Common Mistakes

❌ Using typeof on a type instead of a value

type Person = { name: string };
// ❌ Error: Cannot use 'typeof' with a type
type T = typeof Person;

βœ… Instead:

const person = { name: "Alice" };
type T = typeof person;

πŸ”Œ typeof with Modules or Imported Data

import config from "./config.json";

type ConfigType = typeof config;

This ensures your type stays synchronized with dynamic data.


πŸ“Œ Summary – Recap & Next Steps

The typeof operator in TypeScript allows you to extract types from values and functions, promoting DRY (Don’t Repeat Yourself) principles and maintainability.

πŸ” Key Takeaways:

  • Use typeof to derive a type from a runtime value
  • Combine with keyof, in, ReturnType, Parameters for advanced utilities
  • Enables safer, scalable typing for functions, objects, arrays, and constants

βš™οΈ Real-world relevance:
Perfect for large projects needing robust type consistency, especially in libraries and shared modules.


❓ FAQs

❓ What’s the difference between JS and TS typeof?

βœ… JavaScript’s typeof runs at runtime and returns strings. TypeScript’s typeof in type positions refers to the type of a value at compile time.


❓ Can I use typeof on a function?

βœ… Yes, you can extract the function signature:

function add(a: number, b: number): number {
  return a + b;
}

type AddType = typeof add; // (a: number, b: number) => number

❓ How do I combine typeof with literal types?

Use as const:

const roles = ["admin", "editor"] as const;
type Role = typeof roles[number]; // "admin" | "editor"

Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

TypeScript β€” Typeof Type Operator

Or Copy Link

CONTENTS
Scroll to Top