从声明后的赋值推断出TypeScript类型

时间:2019-02-05 18:42:13

标签: reactjs typescript enzyme

编写针对React组件的测试时,通常会在wrapper块中初始化组件包装器(例如beforeEach),然后在后续测试中使用它。但是,为此,您必须在分配wrapper之前声明wrapper并为其指定显式类型,否则TypeScript将抱怨缺少类型。不幸的是,这种类型的查找/写出可能非常复杂。

在下面的示例中,有什么方法可以“延迟” TypeScript,避免在下面的示例中抱怨wrapper缺少类型,并从{{1} }被分配了?

或者,是否有更好的模式来布置变量以简化键入?

describe('suite', () => {
  // will trigger a no implicit any error
  // but it's quite complex to manually write out the type here
  let wrapper;

  beforeEach(() => {
    const SomeElement = complexFunctionWithGenericParams(someParam);

    // ideally, we want TS to infer the type of `wrapper` from this statement
    wrapper = mountComponent(<SomeElement />);
  })

  it('does something', () => {
    expect(wrapper.state.someField).toBe(5);
  }
}

2 个答案:

答案 0 :(得分:2)

由于要在声明时进行推断,因此无法从赋值中推断类型。测试中局部变量的重点是可以在块之间使用它们,这意味着可以多次分配它们。即使可以进行这种推断,也将是模棱两可的:

let foo; // is the type supposed to be a number, or a string, or both, or any?

it('...', () => {
  foo = 1;
});

it('...', () => {
  foo = 'foo';
});

因此应明确指定类型,例如与ReturnType

let wrapper: ReturnType<typeof mount>;

mount是通用的,返回类型可能有所不同,ReturnType可能是more complicated with generic functions

由于应使用通用参数明确指定酶shallowmount

wrapper = mount<typeof SomeElement, ISomeElementProps>(<SomeElement />);

直接指定通用类型会更直接,因为知道类型是什么(ReactWrapper

let wrapper: Enzyme.ReactWrapper<ISomeElementProps, ISomeElementState, typeof SomeElement>

答案 1 :(得分:0)

尽管不是完全不同的模式,但以下内容有助于在类似情况下摆脱上述警告。

import { shallow, mount, ReactWrapper } from 'enzyme'

describe('suite', () => {
  let wrapper: ReactWrapper;

  beforeEach(() => {
    ...
    wrapper = mount or shallow 
  })

  it('does something', () => {
    ...
  }
}