In TypeScript, I'm writing a function that takes an Error
factory as an argument: either a class name or a factory function. Something like the below:
// 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()
}
}
}
In the above function, errorFactory
can be an Error
class, such that the following code works:
doSomething(0, Error);
Or it can be a function that creates an Error
:
doSomething(0, () => new Error());
The issue is that ClassConstructor
is a TypeScript type, so it doesn't survive compilation to JavaScript.
typeof(Error)
is function
, and so is typeof(()=>{})
.
So how to determine the parameter's type? What should be the test in /* errorFactory is a class constructor */
?