TS typeof
JavaScript has a typeof operator that returns a string. TypeScript adds a type-level typeof that takes a value and gives back its type.
typeof on a value
TS
const user = { id: 1, name: 'Ada' };
type User = typeof user; // { id: number; name: string }
const clone: User = { id: 2, name: 'Linus' };
typeof on a function
TS
function add(a: number, b: number): number {
return a + b;
}
type AddFn = typeof add; // (a: number, b: number) => number
type AddRet = ReturnType<AddFn>; // number
typeof on a const object — keys + values
TS
const STATUS = {
Paid: 'paid',
Pending: 'pending',
Refunded: 'refunded',
} as const;
type StatusObj = typeof STATUS;
type StatusKey = keyof StatusObj; // 'Paid' | 'Pending' | 'Refunded'
type StatusVal = typeof STATUS[StatusKey]; // 'paid' | 'pending' | 'refunded'
typeof for module imports
TS
import config from './config'; type Config = typeof config;
typeof at runtime vs type
TS
// Runtime — JS typeof typeof 42 === 'number'; // Type-level — TS typeof type T = typeof someValue;
Same word, different worlds. The compile-time version operates on identifiers, not on type names.
typeof + as const = single source of truth
TS
const DAYS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] as const; type Day = typeof DAYS[number]; // 'Mon' | 'Tue' | 'Wed' | 'Thu' | 'Fri' // Now both the runtime array and the type stay in sync — change one, the other updates.
Tip:
typeof + as const + indexed access is the Swiss-army-knife pattern for deriving union types from constants. Use it everywhere you'd write the same list twice (once for runtime, once for types).Example
Example
const u = { id: 1, name: 'Ada' };
type U = typeof u; // { id: number; name: string }
const clone: U = { id: 2, name: 'Linus' };
console.log(clone);
Try it Yourself »
Exercise
Type-level operator that grabs the type of a value.
type U =
user;
Six letters.
Discussion
Loading…