TLDR; Checking variable before using it in a anonymous function still TS warns variable possibly undefined
In the below code example variable baseDirId is checked if undefined then passed to array.map function but TS warns baseDirId can be undefined.
const rstr = async (a: string) => {
return a + "bleh"
}
const args: { baseDirId: string | undefined } = {
baseDirId: "someid"
// baseDirId: undefined
}
const someArr = ["bleh1", "bleh2"]
const func1 = async (): Promise<void> => {
try {
// Assume baseDirId can be undefined
let baseDirId = args.baseDirId
// Trigger if baseDirId is undefined
if (!baseDirId) {
const baseDirObj = { id: "valid string" }
baseDirId = baseDirObj.id
}
console.log(typeof baseDirId)
// baseDirId cant be anything other than a string
if (typeof baseDirId !== "string") {
return Promise.reject("Base Dir response invalid")
}
// Why is baseDirId `string | undefined` inside rstr call below even after above checks
const bleharr = someArr.map((val) => rstr(baseDirId))
console.log(await Promise.all(bleharr))
} catch (err) {
console.error(err)
}
}
func1().catch(err => console.error(err))
Is there any possible case where baseDirId can be undefined ?
Why wont TS allow it ? Better way to do it ?
baseDirId as stringto explicitly cast it to string, this is possible because you already made sure it will be string in above code and shouldnt break things, else change the type ofrstrfunction's parameter to matchbaseDirIdbaseDirId as string. Also in the code I make sure the var is notundefined(line 18) then check the only other possible typestring(line 25). Thus I dont understand what you meant by "but that ensures that value of it is string, meaning the type defined is still either a string or undefined."setTimeout(() => console.log(baseDirId), 1000); setTimeout(() => baseDirId = undefined, 500);. Or in other words: A callback might be called at a later point in time, and the value might be undefined then.