Typescript claims it is a CustomType | Undefined, but it should be only CustomType
The problem I have is different, but the core of the problem is listed bellow.
Here is the working code.
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 I want to do user validation logic in different function and throw an error there, the user in passUserToAnotherFunction is 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) // <-- Here user is of type User | undefined and this line is red
const validateExistingUser(user: User | undefined) {
if(!user) {
throw new Error('No user found');
}
}
Why is it behaving like this when this function executes the same lines of code and how to avoid it?
from Recent Questions - Stack Overflow https://ift.tt/3jiPwvT
https://ift.tt/eA8V8J
Comments
Post a Comment