A Case for Typescript
Due too type coercion, unexpected things like these can actually happen:
const nope = Array(10).join("nope" - 1) + " Batman!";console.log(nope); // --> NaNNaNNaNNaNNaNNaNNaNNaNNaN Batman!const a = [ 1, 2, 3 ];
const b = [ 1, 2, 3 ];
console.log(a + b); //-> 1,2,31,2,3
In object oriented programming typeguards, such as typeof or instanceof, are used to determine the type or the class of a variable. This is especially useful with polymorphism (allows to pulgin concrete subclasses into superclass definitions at runtime) to build something like a factory pattern which creates a certain object depending on some inner logic:
Gotcha! This is the first catch. You probably have expected the type of x to be Small and the type of y to be Big since it is common OOP practice. There are two things to know:
- There is no Typescript at runtime. typeof() executes at runtime and therefore has no access to the Typescript type definitions.
Instanceof on the other hand is indeed very useful for us because it actually can determine concrete classes by looking if an object prototype inherits from the prototype of a specified object definition.
For example, p instanceof Person would look if p.prototype inherits Person.protoype. Note, that I purposefully used the word inherit since an object prototype is chained with all its super/base prototypes.
For example, almost all prototypes inherit from Object.prototype
In this example we can see that x’s protoype chains Small, BaseClass, Object in exactly that order. Therfore, an instanceof on those classes returns true, wherase an instanceof on Big returns false.
This means that as long as the prototype is the same, instanceof will return true.