reactjs - 声明后从赋值推断 TypeScript 类型
问题描述
在为 React 组件编写测试时,通常会wrapper
在一个块中初始化一个组件包装器(比如 ),beforeEach
然后在后续测试中使用它。但是,为了做到这一点,你必须wrapper
在赋值之前声明并给它一个显式类型,否则 TypeScript 会抱怨缺少类型。不幸的是,这种类型的计算/写出可能非常复杂。
在下面的示例中,是否有任何方法可以“延迟” TypeScript 抱怨wrapper
以下示例中缺少类型,并让它从wrapper
分配的位置推断类型?
或者,是否有更好的模式来布置变量,使打字更容易?
describe('suite', () => {
// will trigger a no implicit any error
// but it's quite complex to manually write out the type here
let wrapper;
beforeEach(() => {
const SomeElement = complexFunctionWithGenericParams(someParam);
// ideally, we want TS to infer the type of `wrapper` from this statement
wrapper = mountComponent(<SomeElement />);
})
it('does something', () => {
expect(wrapper.state.someField).toBe(5);
}
}
解决方案
没有办法从赋值中推断出类型,因为它应该在声明时推断出来。测试中局部变量的意义在于它们可以在块之间使用,这意味着它们可以被多次赋值。即使这种推断是可能的,它也是模棱两可的:
let foo; // is the type supposed to be a number, or a string, or both, or any?
it('...', () => {
foo = 1;
});
it('...', () => {
foo = 'foo';
});
所以应该明确指定类型,例如ReturnType
:
let wrapper: ReturnType<typeof mount>;
mount
是泛型的,返回类型可能会有所不同,泛型函数ReturnType
可能更复杂。
由于 Enzymeshallow
和mount
应该使用通用参数显式指定:
wrapper = mount<typeof SomeElement, ISomeElementProps>(<SomeElement />);
直接指定泛型类型更直接,因为它知道它是什么类型 ( ReactWrapper
):
let wrapper: Enzyme.ReactWrapper<ISomeElementProps, ISomeElementState, typeof SomeElement>
推荐阅读
- javascript - 如何将节点模块放入汇总包中?
- ios - 将 JSON 数据传递给类中的数组(Alamofire + SwiftyJSON)
- c# - 简单验证
- sql - 比较并获取基于月份插入到表中的新数据
- c++ - 如何在多个 Catch2 测试用例中检查相同的条件
- java - Anylogic - 从其他代理访问变量
- flutter - 在flutter插件中实现外部库android
- google-maps - 具有引用者限制的 API 密钥不能与此 API 一起使用
- laravel - Laravel 5.7 安装问题
- ajax - chrome 上的 Api Url 返回响应,但不是 Postman