Looking for a way to type guard with TypeScript types without using instanceof
:
type Letter = 'A' | 'B';
const isLetter = (c: any): c is Letter => c instanceof Letter; // Error: 'Letter' only refers to a type, but is being used as a value here.
// Desired functionality: Type guard filtering.
isLetter('a'); // Should return true
'foo bar'.split('').filter(c => isLetter(c)); // Should output 'a'
No luck in finding similar issues where instanceof
works differently when used with classes:
class Car {}
const isCar = (c: any): c is Car => c instanceof Car; // No error
isCar('a'); // returns false
If it seems like instanceof
only functions with classes, what alternative could be considered for types and how can we effectively type guard with a TypeScript type
?