【问题标题】:Typescript with async and await: Variable is used before being assigned.ts(2454)带有异步和等待的打字稿:在分配之前使用变量.ts(2454)
【发布时间】:2020-07-16 01:41:14
【问题描述】:

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

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

【问题讨论】:

  • Afaik typescript 不会分析您的行为功能。在不知道act() 的实现细节的情况下,无法保证您的回调在到达expect() 之前完成。
  • 好的,很公平。但是那我应该如何重构代码呢?目前我使用了@ts-ignore,这似乎有帮助,但是......
  • 我也有同样的问题:)。现在,你可以说 renderResult!编译器抱怨的地方。

标签: typescript react-testing-library


【解决方案1】:

您收到此错误,因为您的 tsconfig.json 中有 "strictNullChecks": true。所以编译器会告诉你这个变量的值可能是未定义的。

这里有选项

  • null-object 实例初始化变量(或空值,例如"" 用于String,[] 用于Array 等),
  • 使用 non-null assertion operator (
    expect(renderResult!.container.firstEleme... ),
  • 禁用 strictNullChecks 在您的 tsconfig.json 中,
  • 或任何其他方式 检查未定义或断言该值不是未定义。

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:

      另一种解决方案是将renderResult 标记为RenderResult undefined,然后在末尾使用可选链接访问它。

      test('test', async () => {
        let renderResult: RenderResult | undefined
        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');
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-06
        • 2021-06-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多