typeof 'function' for Callable Types
What you'll learn: How to use typeof to identify and narrow values that are callable functions.
The Core Idea
In JavaScript (and TypeScript), typeof returns the string "function" for any callable value — regular functions, arrow functions, methods, even constructors. This makes it incredibly useful for distinguishing functions from other types of values.
When TypeScript sees a typeof x === "function" check, it narrows the type of x to represent something callable. This is different from checking for "object" (which includes arrays, null, and more) — "function" specifically means "this can be invoked with ()."
Why This Matters
Imagine you have a variable that could be a number or a function that returns a number. Before calling it, you need to know which one you have:
let value: number | (() => number);
if (typeof value === "function") {
// TypeScript knows value is () => number here
const result = value(); // Safe to call
} else {
// TypeScript knows value is number here
const result = value; // Just use it directly
}
The typeof check lets you safely call the function only when it's actually callable, preventing runtime errors.
Common Pattern: Optional Callbacks
This narrowing is especially common with optional callback parameters:
function process(callback?: () => void) {
if (typeof callback === "function") {
callback(); // Safe — TypeScript knows it exists and is callable
}
}
Key Takeaway: typeof value === "function" narrows a value to a callable function type, letting you safely invoke it while TypeScript guarantees type safety.