typeof
Two different typeofs — don't confuse them
typeof exists in both JavaScript and TypeScript, but they operate in different worlds:
- JS
typeof(runtime) — returns a string like"number", used in real code to check values. - TS
typeof(type level) — takes a value and gives you its type, used in type positions.
// JS typeof — runtime narrowing
if (typeof x === "string") { /* ... */ }
// TS typeof — grab the type OF an existing value
const person = { name: "Ajay", age: 23 };
type Person = typeof person; // { name: string; age: number }
Why the type-level typeof is useful
It lets you derive a type from a value you already have, instead of writing the type out twice and keeping them in sync.
const config = {
url: "https://api.example.com",
retries: 3,
debug: false,
};
type Config = typeof config; // { url: string; retries: number; debug: boolean }
Common combo: typeof + keyof
Pair them to get the union of a value's keys or values:
const person = { name: "Ajay", age: 23 };
type Keys = keyof typeof person; // "name" | "age"
type Values = (typeof person)[keyof typeof person]; // string | number
Read it inside-out: typeof person → the type, then keyof → its keys, then index into it → its value types.
The type-level
typeofis a bridge from the value world to the type world — "give me the type of this thing I already built," so your types stay derived and never drift.