首页 > 解决方案 > 覆盖类型以防止不安全的任何调用

问题描述

我使用 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-eslinthttps ://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-test-renderer/index.d.ts - 具体来说,有。no-unsafe-callReactTestInstance{ [propName: string]: any}

我通常想保留这条规则,所以我想避免为每一行禁用它。

我可以创建一个类型定义ReactTestInstance,但是当我这样做时,我也会得到“属性类型props不兼容”。如果我使用铸造也一样。

有没有办法覆盖库类型?除此之外,还有其他建议以这种方式处理不安全类型吗?

标签: reactjstypescript

解决方案


这里最好的解决方案可能是转换props为正确的类型,而不是转换ReactTestInstance为自定义类型。像这样:

await (emailInput.props as EmailInputProps).onChangeText('abc'); 

虽然ReactTestInstance可以进行强制转换(您只需unknown要先强制转换,例如... as unknown as MyCustomType),但将每个道具强制转换为正确的类型将为您提供更准确的总体类型。无论如何,您可能已经很容易获得这些道具的类型。


推荐阅读