Tutorial by Examples

instanceof requires that the variable is of type any. This code (try it): class Pet { } class Dog extends Pet { bark() { console.log("woof"); } } class Cat extends Pet { purr() { console.log("meow"); } } function example(foo: any) { ...
typeof is used when you need to distinguish between types number, string, boolean, and symbol. Other string constants will not error, but won't be used to narrow types either. Unlike instanceof, typeof will work with a variable of any type. In the example below, foo could be typed as number | str...
You can declare functions that serve as type guards using any logic you'd like. They take the form: function functionName(variableName: any): variableName is DesiredType { // body that returns boolean } If the function returns true, TypeScript will narrow the type to DesiredType in any bl...

Page 1 of 1