As a newcomer to typescript, I encountered an issue that hadn't occurred in my previous project. It appears that declaring a variable before an API request inside a try-catch block leads to typescript errors when attempting to use this variable after the try-catch.
Below, you'll find some sample code showcasing this problem.
The problematic variable is res
, placed at the top within 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) {
// Code continuation intended here
}
}
To see the specific TypeScript errors and the tooltip displaying the error, refer to the image included below the question.
This code essentially declares a variable res
before a try-catch block and attempts to utilize it in an if-statement afterward. Inside the try-catch, there's an API request assigning the result to this res
variable upon resolving asynchronously.
If I assign an initial object matching its interface to res
, the error disappears — for example, res = { status: 403, data: ... }
.
I also tested initializing its type with:
let res = AuthApiRes | undefined
Although this resolves the issue, I'm uncertain whether it's considered "cheating" within TypeScript standards.
My goal isn't to assign this variable as an empty placeholder object but rather keep it unassigned until the API response is received.
Is this feasible? If not, how can I eliminate this error without initializing the variable or using a union type of undefined during its declaration?