0

I have a function which gets a class type and I need to know if this class implements an interface before I create an instance of it.

I know how to check if an object instance implements an interface as written in objectIsInstanceOfComponentLoaded and I'm trying to create typeImplementsLoadCompleted

So for the following interface

export interface LoadCompleted {
  loaded: EventEmitter<void>;
}

I need these two functions:

const objectIsInstanceOfLoadCompleted = (object: any): object is LoadCompleted => {
  return 'loaded' in object;
};

// this is what I tried so far
const typeImplementsLoadCompleted = (classType: any): object is LoadCompleted => {
  return classType.prototype.hasOwnProperty('loaded');
};

function createInstance<T>(classType: { new(): T ;} ): T {
    
    if (typeImplementsLoadCompleted(classType)){
       console.log('the class implements LoadCompleted');
    }

    const classTypeObject = new classType();

    if (objectIsInstanceOfComponentLoaded(classTypeObject)){
       console.log('instance of LoadCompleted');
    }
}

  • Does this answer your question? [TypeScript - Check if Class implements an Interface](https://stackoverflow.com/questions/37543588/typescript-check-if-class-implements-an-interface) – Sivakumar Tadisetti Jul 23 '20 at 11:52
  • @SivakumarTadisetti No, I saw this post befeore they are answering the objectIsInstanceOfLoadCompleted question and not type part.. – Michael Goldenberg Jul 23 '20 at 11:56

0 Answers0