resize-observer-polyfill
resize-observer-polyfill copied to clipboard
TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.
Hi, I am new to typescript and I hit a problem with resize-observer-polyfill. When I try to make an instance of ResizeObserver I get: TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. The error sounds like the ResizeObserver type doesn't have a construct(or) signature.
Example code:
import * as ResizeObserver from 'resize-observer-polyfill';
const observer: ResizeObserver = new ResizeObserver((
entries: ResizeObserverEntry[],
observer: ResizeObserver
): void => {
// ...
});
And my typescript configuration:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"baseUrl" : ".",
"rootDir": "src",
"outDir": "lib",
"declaration": true,
"strict": true,
"jsx": "react",
"noImplicitReturns": true,
"noImplicitThis": true,
"noImplicitAny": true,
"strictNullChecks": true,
"paths": {
"*" : ["node_modules/@types/*", "*"]
}
},
"include": [
"src"
]
}
Thanks!
@nikolovp
Typescript is telling you that it does not know that the imported ResizeObserver
can be instantiated like a class, because no type definitions are provided with this module.
You can overcome this by explicitly declaring the type as any
like this:
import * as ResizeObserver from 'resize-observer-polyfill';
const _ResizeObserver: any = ResizeObserver;
const observer: ResizeObserver = new _ResizeObserver((
entries: ResizeObserverEntry[],
observer: ResizeObserver
): void => {
// ...
});
@nikolovp You need to use the default export of the resize-observer-polyfill
module:
import ResizeObserver from 'resize-observer-polyfill';
//...
@que-etc This is the first thing I actually did but in that case ResizeObserver is undefined so I tried with importing everything as ResizeObserver and I finally got the construct function but I cannot instantiate it without workarounds like the one mentioned by @ablamunits. However declaring a callback of type ResizeObserverCallback does not throw any errors so I guess the type definitions are successfully loaded.
@nikolovp Please, add esModuleInterop
to your config file:
{
"compilerOptions": {
// ...
"esModuleInterop": true
}
}
I didn't know about this compiler options. It works now. Thanks a lot!