带有异步和等待的打字稿:在分配之前使用变量.ts(2454)

ger*_*lus 11 typescript react-testing-library

为什么打字稿在这里抱怨变量未分配?我是否遗漏了一些明显的范围?

test('test', async () => {
  let renderResult: RenderResult;
  await act(async () => {
    renderResult = render(<Component />);
  });

  await act(async () => {
    renderResult.rerender(<Component />);
  });
  // ERRROR: Variable 'renderResult' is used before being assigned.ts(2454)
  expect(renderResult.container.firstElementChild!.getAttribute('src')).toBe('original');
});
Run Code Online (Sandbox Code Playgroud)

Dmi*_*lov 6

您收到此错误,因为您"strictNullChecks": true的 tsconfig.json 中有此错误。因此编译器会向您显示该变量可能具有未定义的值。

这里的选项有

  • 使用空对象实例(或空值,如""字符串、[]数组等)初始化变量,
  • 使用 非空断言运算符(
    expect(renderResult!.container.firstEleme... ),
  • strictNullChecks在 tsconfig.json 中禁用 ,
  • 或检查未定义或断言值不是未定义的任何其他方式。

但恕我直言,如果您正在使用strictNullChecks,您应该考虑使用空对象模式。


ada*_*amC 0

编译器会抱怨,因为它是未定义的,并且您在使用它之前没有检查它。此外,正如前面所说,编译器无法知道异步函数内部发生了什么,因此它无法知道它最终是否被分配。

你可以使用expect(renderResult?.container?.firstElementChild!.getAttribute('src')).toBe('original');

因此,如果该链中的任何内容未定义,您将得到“假”。