TypeScript
/Advanced
typeof Operator (in Types)
Definition
In the type context, `typeof` takes a JavaScript variable or object and generates a TypeScript Type based on its shape.
Explain Like I'm New
Usually, you write the Type first (the blueprint), and then build the Object (the house). But sometimes, you already have the Object, and you want to auto-generate the blueprint from it. `typeof` points a scanner at a JS variable and extracts its shape into a TS Type.
Real World Example
You have a massive, deeply nested configuration object `const config = { theme: 'dark', api: { url: '...' } }`. Instead of writing out a 50-line interface manually, you just do `type ConfigType = typeof config;`.
Common Use Cases
- •Extracting types from JSON objects
- •Extracting the signature of an existing function
Interactive Example
Loading Code Playground...
Interview Questions
basic
- What is the difference between JS `typeof` and TS `typeof`?
intermediate
- Can you use TS `typeof` on a function to get its signature?
advanced
- How do you combine `typeof` and `keyof`?