instanceof with Built-in Classes
You'll learn how to use instanceof to narrow types when working with JavaScript's built-in classes like Date, Error, RegExp, and Array.
The Power of instanceof with Standard Classes
You've seen how instanceof works with your own custom classes. But JavaScript comes with many built-in classes, and instanceof is just as useful for narrowing those types!
When you have a union type that includes built-in classes, TypeScript can narrow the type based on instanceof checks, giving you access to class-specific methods and properties.
Common Built-in Classes
Date Objects
function formatValue(value: string | Date) {
if (value instanceof Date) {
// TypeScript knows: value is Date
return value.toISOString();
}
// TypeScript knows: value is string
return value.toUpperCase();
}
Error Objects
function handleResult(result: string | Error) {
if (result instanceof Error) {
// TypeScript knows: result is Error
console.error(result.message);
return;
}
console.log(result);
}
Regular Expressions
function testPattern(pattern: string | RegExp, text: string) {
if (pattern instanceof RegExp) {
// TypeScript knows: pattern is RegExp
return pattern.test(text);
}
return text.includes(pattern);
}
Arrays
function getLength(value: string | Array<number>) {
if (value instanceof Array) {
// TypeScript knows: value is number[]
return value.reduce((sum, n) => sum + n, 0);
}
return value.length;
}
Why This Matters
Built-in classes have rich APIs with many methods. Using instanceof ensures you only call those methods when the value is actually the right type, preventing runtime errors.
Key Takeaway: Use instanceof with built-in classes like Date, Error, RegExp, and Array to safely narrow union types and access class-specific methods.