Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript with async and await: Variable is used before being assigned.ts(2454)

Why is typescript complaining here that variable is unassigned? Am I missing something obvious with scopes?

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');
});
like image 516
gerasalus Avatar asked Apr 03 '20 19:04

gerasalus


People also ask

Is used before being assigned TypeScript?

The error "Variable is used before being assigned" occurs when we declare a variable without assigning a value to it or only assign a value if a condition is met. To solve the error, change the variable's type to be possibly undefined or give it an initial value.

Does TypeScript support async await?

async / await support in ES6 targets (Node v4+)TypeScript now supports asynchronous functions for engines that have native support for ES6 generators, e.g. Node v4 and above.


1 Answers

You are getting this error, because you have "strictNullChecks": true in your tsconfig.json. So the compiler shows you that the variable is possibly has value of undefined.

Options here are

  • to initialize the variable with a null-object instance (or empty values like "" for String, [] for Array, etc),
  • to use non-null assertion operator (
    expect(renderResult!.container.firstEleme... ),
  • disable the strictNullChecks in your tsconfig.json,
  • or any other way of checking for undefined or asserting the value to be not undefined.

But IMHO if you are using strictNullChecks, you should consider using null-object pattern.

like image 67
Dmitry Shapovalov Avatar answered Sep 18 '22 08:09

Dmitry Shapovalov