[英]Overriding types to prevent unsafe any calls
I have some tests in React Native using the react-test-renderer such as:我在 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');
});
This works fine, but @typescript-eslint
is complaining about no-unsafe-call
because of the type declarations returned by ReactTestInstance: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-test-renderer/index.d.ts -- specifically, ReactTestInstance
has { [propName: string]: any}
.这工作正常,但
@typescript-eslint
抱怨no-unsafe-call
因为 ReactTestInstance 返回的类型声明: https : //github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-test-renderer/ index.d.ts —— 具体来说, ReactTestInstance
有{ [propName: string]: any}
。
I generally want to keep this rule, so I want to avoid disabling it for every line.我通常想保留这个规则,所以我想避免对每一行禁用它。
I can create a type definition for ReactTestInstance
, but when I do that, I also get "types of property props
are incompatible."我可以为
ReactTestInstance
创建一个类型定义,但是当我这样做时,我也会得到“属性props
类型不兼容”。 Same if I use casting.如果我使用铸造也是如此。
Is there any way to override library types?有没有办法覆盖库类型? Beyond that, are there any other suggestions to handle the unsafe type in this way?
除此之外,还有其他建议可以以这种方式处理不安全类型吗?
The best solution here is probably going to be to cast props
to correct type, rather than casting ReactTestInstance
to a custom type.这里最好的解决方案可能是将
props
为正确的类型,而不是将ReactTestInstance
转换为自定义类型。 Like so:像这样:
await (emailInput.props as EmailInputProps).onChangeText('abc');
While casting ReactTestInstance
is possible (you just need cast to unknown
first, eg ... as unknown as MyCustomType
), casting each of the props to their correct types instead will give you more accurate types overall.虽然转换
ReactTestInstance
是可能的(您只需要首先转换为unknown
,例如... as unknown as MyCustomType
),但将每个道具转换为正确的类型将为您提供更准确的整体类型。 You probably have a type for those props easily available already anyway.无论如何,您可能已经有一种很容易获得的道具类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.