Typeof

3 snippets across 2 stacks — TypeScript, JavaScript

TSTypeScript

typeof Guard

TS · Type Guards & Narrowing
syntax
if (typeof value === "string") { ... }
example
function formatValue(input: string | number | boolean): string {
  if (typeof input === "string") {
    return input.toUpperCase();
  }
  if (typeof input === "number") {
    return input.toFixed(2);
  }
  return input ? "Yes" : "No";
}
output
// TypeScript narrows the type inside each branch automatically

Note typeof works for: "string", "number", "boolean", "undefined", "symbol", "bigint", "function", "object". Note: typeof null === "object" — this is a famous JavaScript quirk that TypeScript inherits.

keyof & typeof Operators

TS · Advanced Types
syntax
type Keys = keyof Type;
type ValueType = typeof runtimeValue;
example
interface Product {
  id: string;
  name: string;
  price: number;
}

type ProductKey = keyof Product; // "id" | "name" | "price"

function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] {
  return items.map(item => item[key]);
}

// typeof: extract type from a runtime value
const defaultSettings = {
  volume: 50,
  brightness: 80,
  darkMode: true,
};

type Settings = typeof defaultSettings;
// { volume: number; brightness: number; darkMode: boolean }
output
// keyof extracts property names; typeof extracts the type of a value

Note keyof works on types; typeof works on values. They are often combined: keyof typeof myObject gives you the union of property names of a runtime object. typeof only works with variables and properties, not with arbitrary expressions like function calls.

JSJavaScript

typeof Operator

JS · Data Types
syntax
typeof value
example
console.log(typeof "hello");    // "string"
console.log(typeof 42);         // "number"
console.log(typeof true);       // "boolean"
console.log(typeof undefined);  // "undefined"
console.log(typeof null);       // "object" (!)  
console.log(typeof []);         // "object"
console.log(typeof (() => {})); // "function"

Note typeof null === "object" is a historic bug that will never be fixed. Use value === null for null checks. Arrays report as "object" -- use Array.isArray() instead.