首页 > 解决方案 > 声明后从赋值推断 TypeScript 类型

问题描述

在为 React 组件编写测试时,通常会wrapper在一个块中初始化一个组件包装器(比如 ),beforeEach然后在后续测试中使用它。但是,为了做到这一点,你必须wrapper在赋值之前声明并给它一个显式类型,否则 TypeScript 会抱怨缺少类型。不幸的是,这种类型的计算/写出可能非常复杂。

在下面的示例中,是否有任何方法可以“延迟” TypeScript 抱怨wrapper以下示例中缺少类型,并让它从wrapper分配的位置推断类型?

或者,是否有更好的模式来布置变量,使打字更容易?

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);
  }
}

标签: reactjstypescriptenzyme

解决方案


没有办法从赋值中推断出类型,因为它应该在声明时推断出来。测试中局部变量的意义在于它们可以在块之间使用,这意味着它们可以被多次赋值。即使这种推断是可能的,它也是模棱两可的:

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可能更复杂

由于 Enzymeshallowmount应该使用通用参数显式指定:

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

直接指定泛型类型更直接,因为它知道它是什么类型 ( ReactWrapper):

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

推荐阅读