Petites recettes TypeScript

Tester l'héritage

class R {}
class P extends R {}
class C extends P {}
 
console.log('object   ', (new C) instanceof R)     //> true
console.log('prototype', C.prototype instanceof R) //> true
console.log('direct   ', C instanceof R)           //> false
 
// Deux en un
 
type Type = new(...args:any[])=>object
const instanceOf = (object:object|Type, type:Type) =>
	(typeof object !== 'object') ? (object.prototype instanceof type) : (object instanceof type)
 
console.log('object   ', instanceOf(new C, R)) //> true
console.log('prototype', instanceOf(C, R))     //> true