Currently, I am incorporating the await-to-js library for handling errors (specifically utilizing the to
method from the library).
In an intriguing scenario, the variable type shifts to string | undefined
within a for..of
loop, whereas outside of the loop, the same variable holds the type string
.
Take a look at this example involving the testMethod
:
function to<T, U = Error>(
promise: Promise<T>,
errorExt?: object
): Promise<[U, undefined] | [null, T]> {
return promise
.then<[null, T]>((data: T) => [null, data])
.catch<[U, undefined]>((err: U) => {
if (errorExt) {
const parsedError = Object.assign({}, err, errorExt);
return [parsedError, undefined];
}
return [err, undefined];
});
}
async function retrieveAccessToken(): Promise<string> {
const randomNumber = Math.random();
if(randomNumber < 0.5) {
throw new Error("Failed");
}
return "testToken";
}
function printAccessToken(accessToken: string) {
console.log(accessToken);
};
async function testMethod(): Promise<boolean> {
const accessTokenPromise = retrieveAccessToken();
const [err, accessToken] = await to(accessTokenPromise);
if(err){
console.log("Failed");
return false;
}
// No error here
printAccessToken(accessToken);
for(let i = 0 ; i < 5; i++){
// The issue arises here! Type Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
printAccessToken(accessToken);
}
return true;
}
This peculiar situation appears to be addressed by introducing an "if" check on accessToken like so: if(!accessToken)
. However, it remains puzzling why the type of accessToken
toggles between string | undefined
inside and string
outside of the for loop?