The typeof operator returns a string identifying its operand's type. Use it to validate JavaScript values at runtime before performing type-dependent work, especially when a function may receive unexpected data. section 3.4.2
Rejecting an unexpected argument
function myFunction(param) { if (typeof(param) == "number") { let result = param + 100; console.log("My result: " + result); } else { throw ("Expected a number: " + param); } } myFunction(1); myFunction("London"); The number produces 101; the string triggers an error instead of being converted and concatenated into London100. section 3.4.2
In TypeScript, typeof checks also help distinguish branches involving multiple types:
- A parameter declared as number | string cannot use operations that belong to only one member until the code checks its type. section 3.4.2
- Checking typeof(param) == "number" permits number-specific operations such as toFixed; the alternative branch handles the string case. section 3.4.2
- TypeScript's declared parameter types can make a runtime typeof guard unnecessary when the compiler rejects invalid calls. section 3.4.2
Listing 4.27. Checking an object type in the main.ts file in the src folder
class Product {
constructor(public name: string, public price: number,
public category?: string) {
}
printDetails() {
if (this.category != undefined) {
console.log(`Name: ${this.name}, Price: ${this.price}, ` +
`Category: ${this.category}`);
} else {
console.log(`Name: ${this.name}, Price: ${this.price}`);
}
}
}
class DiscountProduct extends Product {
constructor(name: string, price: number, private discount: number) {
super(name, price - discount);
}
}
let hat = new DiscountProduct("Hat", 100, 10);
let boots = new Product("Boots", 100, "Snow Gear");
// hat.printDetails();
// boots.printDetails();
console.log(`Hat is a Product? ${hat instanceof Product}`);
console.log(`Hat is a DiscountProduct? ${hat instanceof DiscountProduct}`);
console.log(`Boots is a Product? ${boots instanceof Product}`);
console.log("Boots is a DiscountProduct? "
+ (boots instanceof DiscountProduct));
For objects, typeof reports object rather than identifying the class; use instanceof when checking whether an object derives from a class or superclass. section 4.4.3


