theory.ts

Type Guards

Type Narrowing with typeof

The `typeof` operator is used to check primitive types and narrow down the possible values.

  • Works with `string`, `number`, `boolean`, `symbol`, `undefined`, and `object`.
  • Helps ensure type safety in conditional logic.
  • Useful for handling function parameters of multiple types.
// Using typeof for type narrowing
function processInput(value: string | number) {
  if (typeof value === "string") {
    console.log(value.toUpperCase()); // Safe, value is a string
  } else {
    console.log(value.toFixed(2)); // Safe, value is a number
  }
}

processInput("hello"); // "HELLO"
processInput(3.14159); // "3.14"