我正在使用Typescript和Enzyme来测试反应组分。我对Typescript很新。
我在测试中有这个辅助函数:
const getComponent = (mountFn = shallow) => (
mountFn(<Component />)
)
当我将其作为getComponent()
运行时,此功能正常运行,但是一旦getComponent(mount)
运行它就会失败,因为typescript假定getComponent
返回ShallowWrapper。
我有几个问题:
mountFn
可以是shallow
还是mount
?ShallowWrapper
或ReactWrapper
类型?ShallowWrapper
传递时应为shallow
类型,在传递ReactWrapper
时应为mount
?答案 0 :(得分:1)
如何告诉Typescript
mountFn
可以浅或挂载?
这样就可以了。
import {ShallowWrapper, ReactWrapper} from 'enzyme';
type mountFnType<P, S> = (node: React.ReactElement<P>, options?: any): ShallowWrapper<P, S> | ReactWrapper<P, S>
const getComponent = <P, S>(mountFn: mountFnType<P, S>) => (
mountFn(<Component />)
)
如果您希望可以使用union types为ShallowWrapper
和ReactWrapper
创建类型别名。
type Wrapper<P, S> = ShallowWrapper<P, S> | ReactWrapper<P, S>;
现在,你的功能看起来像,
type mountFnType<P, S> = (node: React.ReactElement<P>, options?: any) => Wrapper<P, S>;
const getComponent = <P, S>(mountFn: mountFnType<P, S>) => (
mountFn(<Component />)
)
如何告诉它返回值可以是ShallowWrapper或ReactWrapper类型?
添加返回类型
const getComponent = <P, S>(mountFn: mountFnType<P, S>): Wrapper<P, S>
理想情况下 - 如何判断返回值在浅层传递时应为ShallowWrapper类型,在传递mount时是否为ReactWrapper?
您无需手动指定。
如何使用已在@ types / enzyme中定义的打字输出?
我们已经在shallow
使用mount
和@types/enzyme
的类型定义。
这是一个很好的做法吗?在使用打字稿之前,我曾经一直这样做,但也许我应该创建两个独立的函数?
我猜,这只是一个偏好问题。您可以使用辅助函数使一些工作更容易。如果我在你的位置,我也会将组件作为第二个参数传递。所以最后你的代码看起来像,
import {ShallowWrapper, ReactWrapper} from 'enzyme';
type Wrapper<P, S> = ShallowWrapper<P, S> | ReactWrapper<P, S>;
type mountFnType<P, S> = (node: React.ReactElement<P>, options?: any) => Wrapper<P, S>;
const getComponent = <P, S>(mountFn: mountFnType<P, S>, CustomComponent: React.ComponentClass<P>): Wrapper<P, S> => {
return mountFn(<CustomComponent />);
};
希望这会有所帮助:)