As I work with TypeScript, I am creating a function that accepts an error factory as an argument. This factory can be either a class name or a function. The function looks something like this:
// Alias from class-transformer package
type ClassConstructor<T> = {
new (...args: any[]): T;
};
function doSomething(value: number, errorFactory: () => Error | ClassConstructor<Error>) {
if (value === 0) {
// Zero is not allowed
if (/* errorFactory is a class constructor */) {
throw new errorFactory()
} else {
throw errorFactory()
}
}
}
Within this function, the errorFactory
parameter can accept an Error
class:
doSomething(0, Error);
Or it can receive a function that generates an Error
:
doSomething(0, () => new Error());
The challenge arises because ClassConstructor
is a type specific to TypeScript and does not retain its structure when compiled to JavaScript.
The typeof(Error)
is recognized as a function
, just like typeof(()=>{})
.
So how can we determine the parameter's type? What condition should we use in the comment section for
/* errorFactory is a class constructor */
?