Home > OS >  TypeScript: type of class that implements a certain interface or method
TypeScript: type of class that implements a certain interface or method

Time:12-21

Goal

I wanna have a type that describes an object with values of type: Array<ClassRef> where ClassRef is any class that must implement a certain interface.

Approach

type KeyClassMap<SomeUnionType> = {
   [key in keyof SomeUnionType]: Array<ClassRef>
} 

type ClassRef = new (...args: any[]) => any // should extend that interface

interface I {
   [Symbol.hasInstance](hint: string): boolean
}

const _map: KeyClassMap<UnionType> = {
   myKey: [Date, MyOwnClass, MyOtherClass] // <- all these should have implemented Symbol.hasInstance to check with `instanceof` operator
}

Question

The example misses a declaration of a class that implements that interface. I am not sure how to do that.

Each class should only implement this one method ([Symbol.hasInstance]) to check if a value is an instance of that class.

I would like to know how to declare a type of a class that implements that interface or any other way to describe a class that has this method.

I assume that this is not really possible, so I appreciate any other tips.

CodePudding user response:

When defining your ClassRef type you are really specifying the type of its constructor function. As the constructor function returns an instance of the class you can force the class to implement a specific interface by forcing the return value of its constructor to implement that interface. Your code should look like this:

type ClassRef<T> = new (...args: any[]) => T;

type KeyClassMap<SomeUnionType> = {
   [key in keyof SomeUnionType]: Array<ClassRef<I>>
} 

If you want to use the KeyClassMap type in other places as well, you can of course add another generic to it instead of statically using the I interface.

  • Related