[英]Overriding types to prevent unsafe any calls
我在 React Native 中使用 react-test-renderer 进行了一些测试,例如:
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');
});
这工作正常,但@typescript-eslint
抱怨no-unsafe-call
因为 ReactTestInstance 返回的类型声明: https : //github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-test-renderer/ index.d.ts —— 具体来说, ReactTestInstance
有{ [propName: string]: any}
。
我通常想保留这个规则,所以我想避免对每一行禁用它。
我可以为ReactTestInstance
创建一个类型定义,但是当我这样做时,我也会得到“属性props
类型不兼容”。 如果我使用铸造也是如此。
有没有办法覆盖库类型? 除此之外,还有其他建议可以以这种方式处理不安全类型吗?
这里最好的解决方案可能是将props
为正确的类型,而不是将ReactTestInstance
转换为自定义类型。 像这样:
await (emailInput.props as EmailInputProps).onChangeText('abc');
虽然转换ReactTestInstance
是可能的(您只需要首先转换为unknown
,例如... as unknown as MyCustomType
),但将每个道具转换为正确的类型将为您提供更准确的整体类型。 无论如何,您可能已经有一种很容易获得的道具类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.