Sometimes, we want to fix the "is not newable" error when passing class as parameter with TypeScript.
In this article, we’ll look at how to fix the "is not newable" error when passing class as parameter with TypeScript.
How to fix the "is not newable" error when passing class as parameter with TypeScript?
To fix the "is not newable" error when passing class as parameter with TypeScript, we can create a interface with the new
keyword and then use that as the type of the class parameter.
For instance, we write
interface IMyClass {
new (name: string): MyClass;
}
const test = (MyClass: IMyClass) => {
const obj = new MyClass("hello");
};
to create the IMyClass
interface that has the new
property with the signature being the MyClas
constructor’s signature and the type set to MyClass
.
Then we set that as the type of the MyClass
parameter in the test
function and then we can create a new MyClass
instance in the function without errors.
Conclusion
To fix the "is not newable" error when passing class as parameter with TypeScript, we can create a interface with the new
keyword and then use that as the type of the class parameter.