Intermediate LevelJavaScript & TypeScript
What are keyof and typeof type operators in TypeScript?
❓ Interview Prompt: Explain keyof indexed type query operator and typeof type query operator in type positions.
TypeScript includes two powerful type operators for querying shapes and keys:
1. keyof (Type Operator):
Takes an object type and produces a string or number literal union of its property keys.
•
type UserKeys = keyof User; → "id" | "name" | "email"2. typeof (In Type Position):
Refers to the type of a JavaScript variable or object instance within type annotations (distinct from JS runtime typeof).
Code Implementation Example
typescript
const defaultConfig = {
env: 'production',
port: 8080,
debug: false
};
// 1. typeof captures type shape of JS variable
type Config = typeof defaultConfig;
// Equivalent to: { env: string; port: number; debug: boolean; }
// 2. keyof extracts union of key names
type ConfigKeys = keyof Config; // "env" | "port" | "debug"
// Type-safe property getter function
function getSetting<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const port = getSetting(defaultConfig, 'port'); // TS infers return type as number!💡Capturing variable structure with typeof and creating key unions with keyof.
🎯 Interview Key Takeaway
typeof extracts the TypeScript type from a runtime value; keyof extracts a literal union of object keys.
#TypeScript#keyof#typeof#Intermediate
Back to all JavaScript & TypeScript Questions→