Home > database >  Typescript generic class as function parameter
Typescript generic class as function parameter

Time:10-21

I have two unrelated classes and a function that interacts with the constructor.name I don't want to use the any type. Is there a way I can write the following in a typescript way? I want someClass to represent any class but I'm not exactly sure how to write that.

class MyClass {
    //
}

class MyOtherClass {
    // 
}

const getClassName = (someClass, name = someClass.constructor.name) => {
    console.log(someClass)
    console.log(someClass.constructor.name)
}

getClassName(MyClass)

CodePudding user response:

You can define the type for a class constructor, like this:

type ClassConstructor<T> = {
  new (...args: any[]): T;
};

const getClassName = (someClass: ClassConstructor<any>) => {
    console.log(someClass.name)
}

getClassName(MyClass)
getClassName(MyOtherClass)
// this is a complie error: not a constructor
getClassName(() => 1)
// this is a complie error: instance - not a class
getClassName(new MyClass())

Playground Example

But beware, that the class-name may be different in production: i.e. when you use webpack to minify/uglify your code

CodePudding user response:

Type of constructor.name is string and type of someClass is Object, so you can use Object and string.

  • Related