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?
CodePudding user response:
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 ¶es
, but you will lose typescript checks, and for me, it is not worth.