reactjs - 覆盖类型以防止不安全的任何调用
问题描述
我使用 react-test-renderer 在 React Native 中进行了一些测试,例如:
it('should keep login button disabled', async () => {
const emailInput = root.findByProps({ testID: 'EmailInput' });
const passwordInput = root.findByProps({ testID: 'PasswordInput' });
await act(async () => {
await emailInput.props.onChangeText('abc');
await passwordInput.props.onChangeText('abc');
});
const loginButton = root.findByProps({ testID: 'LoginButton' });
expect(loginButton.props.type).toBe('disabled');
});
这工作正常,但由于 ReactTestInstance 返回的类型声明而抱怨:@typescript-eslint
https ://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-test-renderer/index.d.ts - 具体来说,有。no-unsafe-call
ReactTestInstance
{ [propName: string]: any}
我通常想保留这条规则,所以我想避免为每一行禁用它。
我可以创建一个类型定义ReactTestInstance
,但是当我这样做时,我也会得到“属性类型props
不兼容”。如果我使用铸造也一样。
有没有办法覆盖库类型?除此之外,还有其他建议以这种方式处理不安全类型吗?
解决方案
这里最好的解决方案可能是转换props
为正确的类型,而不是转换ReactTestInstance
为自定义类型。像这样:
await (emailInput.props as EmailInputProps).onChangeText('abc');
虽然ReactTestInstance
可以进行强制转换(您只需unknown
要先强制转换,例如... as unknown as MyCustomType
),但将每个道具强制转换为正确的类型将为您提供更准确的总体类型。无论如何,您可能已经很容易获得这些道具的类型。
推荐阅读
- html - jekyll-seo-tag:包括前面的“标签”属性
- c# - Oracle UDT 映射与 .Net 自定义类型包的类型映射问题
- c# - 如何使用 WinForms 使 MenuStrip 与关闭/最小化按钮处于同一级别?
- python - Numpy数组:如何根据列中的值提取整行
- algorithm - 创建易于记忆且不易出错的数字的算法
- python - 高斯过程回归增量学习
- javascript - d3 fitExtent 函数未映射 GeoJSON
- reactjs - 带有 react 包的 Yarn 工作区,适用于 babel,不适用于 babel+webpack(?)
- sql - 如何克服这个问题。如果经理不可用,则显示经理名称“NA”。如果电话号码不可用,则显示为“NA”
- c# - 在 Pivot selected Item 更改 UWP 上隐藏子网格