resize-observer-polyfill icon indicating copy to clipboard operation
resize-observer-polyfill copied to clipboard

TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.

Open pnpetrov opened this issue 6 years ago • 5 comments

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!

pnpetrov avatar Mar 10 '18 17:03 pnpetrov

@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 => {
	// ...
});

ablamunits avatar Mar 11 '18 14:03 ablamunits

@nikolovp You need to use the default export of the resize-observer-polyfill module:

import ResizeObserver from 'resize-observer-polyfill';
//...

que-etc avatar Mar 11 '18 15:03 que-etc

@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.

pnpetrov avatar Mar 11 '18 16:03 pnpetrov

@nikolovp Please, add esModuleInterop to your config file:

{
    "compilerOptions": {
        // ...
        "esModuleInterop": true
    }
}

que-etc avatar Mar 11 '18 17:03 que-etc

I didn't know about this compiler options. It works now. Thanks a lot!

pnpetrov avatar Mar 11 '18 18:03 pnpetrov