繁体   English   中英

覆盖类型以防止不安全的任何调用

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM