Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is right way to use global package with TypeScript?

I am using global package to enable using some methods of enzyme in my tests files without importing:

import { configure, shallow, render, mount } from 'enzyme';
   .....
global.shallow = shallow;
global.render = render;
global.mount = mount;

So I am able to write

const component = shallow(<Input {...props} />);

in my test file without import of shallow method

But typescript doesn't know about this and I get error: [ts] Cannot find name 'shallow'.

How can I tell to typescript about these globals?

like image 561
Yuriy Avatar asked Jan 19 '26 14:01

Yuriy


1 Answers

That's what declare is used for. Add the following line to the top of your test file:

declare const shallow:any; // Maybe more specific type information if you have;

Instead of using declare, you could also typecast the window object like this:

const component = (window as any).shallow(<Input {...props} />);

or like this:

const component = (<any> window).shallow(<Input {...props} />);

But keep in mind, exposing functions as global objects is not a good practice. Especially when you have two functions of the same name, as one will override the other.

like image 103
pascalpuetz Avatar answered Jan 22 '26 02:01

pascalpuetz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!