在 TypeScript 中使用全局包的正确方法是什么?
What is right way to use global package with TypeScript?
我正在使用 global 包来启用在我的测试文件中使用一些酶的方法而无需导入:
import { configure, shallow, render, mount } from 'enzyme';
.....
global.shallow = shallow;
global.render = render;
global.mount = mount;
所以我可以写
const component = shallow(<Input {...props} />);
在我的测试文件中没有导入 shallow
方法
但是打字稿不知道这个,我得到错误:
[ts] Cannot find name 'shallow'.
我如何告诉打字稿这些全局变量?
这就是 declare
的用途。将以下行添加到测试文件的顶部:
declare const shallow:any; // Maybe more specific type information if you have
;
除了使用 declare,您还可以像这样对 window 对象进行类型转换:
const component = (window as any).shallow(<Input {...props} />);
或者像这样:
const component = (<any> window).shallow(<Input {...props} />);
但请记住,将函数公开为全局对象并不是一个好的做法。尤其是当你有两个同名函数时,一个会覆盖另一个。
我正在使用 global 包来启用在我的测试文件中使用一些酶的方法而无需导入:
import { configure, shallow, render, mount } from 'enzyme';
.....
global.shallow = shallow;
global.render = render;
global.mount = mount;
所以我可以写
const component = shallow(<Input {...props} />);
在我的测试文件中没有导入 shallow
方法
但是打字稿不知道这个,我得到错误:
[ts] Cannot find name 'shallow'.
我如何告诉打字稿这些全局变量?
这就是 declare
的用途。将以下行添加到测试文件的顶部:
declare const shallow:any; // Maybe more specific type information if you have
;
除了使用 declare,您还可以像这样对 window 对象进行类型转换:
const component = (window as any).shallow(<Input {...props} />);
或者像这样:
const component = (<any> window).shallow(<Input {...props} />);
但请记住,将函数公开为全局对象并不是一个好的做法。尤其是当你有两个同名函数时,一个会覆盖另一个。