1

Being relatively new to typescript, I've run into a problem that I didn't face in my first project - when declaring a variable prior to an api request inside a try-catch seems to throw typescript errors for operations on this variable after the try-catch.

I've written sample code to show the issue below.

The res is the variable with the issue in question, at the top inside the if statement.

  interface AuthApiData {
      message: string;
      success: boolean;
    }

    interface AuthApiRes {
      status: number;
      data: AuthApiData;
    }

    if (router.pathname !== '/login') {
      let res: AuthApiRes;
      
      let status;
      const authenticate = async () => {
        try {
          res = await axiosPrivate.get('/api/gilat');
          status = res?.status;
        } catch (err) {
          console.log('authflow err:', err);
        }
      };

      authenticate();

      if (status === 200 && res?.data?.success === true) {
        // I wanted to continue writing code here
      }
    }

In case anyone wanted to see where typescript was throwing errors and the error appearing on the tooltip I've put an image at the bottom of the question.

All the code does here is declare a variable res before a try-catch statement, then try to use this variable in an if-statement after. Inside the try-catch there is an api request that sets the result to this res variable when the asynchronous request is resolved.

If I declare res to be some initial object befitting of the it's interface the error goes away, e.g. res = { status: 403, data: ... }.

I also tried initializing its type with:

let res = AuthApiRes | undefined

Which fixes the problem but I find it messy or rather I'm unsure if this is just "cheating" typescript.

I don't wish to initialize this variable into this an empty placeholder object, but rather for it to remain unassigned until the api resolves.

Is this possible, and if not how can I remove this error without initializing the variable or setting a union "or" undefined for it's typing during its declaration?

Tooltip error and typescript underline errors

Darkphoton
  • 506
  • 4
  • 14
  • As always, post *the actual code*, not images of code – CertainPerformance Mar 28 '22 at 06:02
  • @CertainPerformance my apologies, my original intent was to show the popup of the errors as well as the underlines of where the errors were cuz of typescript else i thought it may be difficult to pinpoint where typescript was highlighting as errors. I guess i could have written it out. Will edit into actual code in a bit. – Darkphoton Mar 28 '22 at 06:09

1 Answers1

2

I also tried initializing its type with:

let res: AuthApiRes | undefined

Which fixes the problem but I find it messy or rather I'm unsure if > this is just "cheating" typescript.

When a variable is declared but not initialized, its value is undefined, for this typescript does not complain when you add undefined with the union.

For me the best way is to initialize res to null, and then check it:


let res: AuthApiRes | null = null;

if(res) {
  if(status === 200 && res.data?.success === true) {
    ...
  }
}

The same with the status variable.

If you do not like this approach, you could prefix res with !

let res!: AuthApiRes

This hints typescript that you will actually assign a value to res, but you will lose typescript checks, and for me, it is not worth.

Nullndr
  • 1,624
  • 1
  • 6
  • 24
  • 1
    Thanks, I can accept this I guess. I was mainly afraid there was something wrong with my using a union here but it seems like it's not abnormal to do so in this situation. And also appreciate the tip on the !, I didn't know that existed but I concur - it's probably not worth it. – Darkphoton Mar 28 '22 at 07:48