The issue at hand is unique, but the root of the problem can be found below. Typescript Playground link for this particular issue
Below is a snippet of code that works without any errors.
type User = {
name: string;
}
let user: User | undefined
user = await UserService.getUserById(1)
if(!user) {
throw new Error('No user found');
}
await passUserToAnotherFunction(user) // <-- 'user' is defined here and of type 'User'
If attempting to validate the user in a separate function and encountering an error in 'passUserToAnotherFunction', the 'user' object becomes of type 'User | undefined'. Here is an example:
type User = {
name: string;
}
let user: User | undefined
user = await UserService.getUserById(1)
validateExistingUser(user)
await passUserToAnotherFunction(user) // <-- In this instance, 'user' is of type 'User | undefined' and throws a red flag
const validateExistingUser(user: User | undefined) {
if(!user) {
throw new Error('No user found');
}
}
Why does this discrepancy occur when both functions execute the same code lines, and how can it be prevented?