I am currently facing an issue with a function that resembles the one provided below (I have created a simplified example for discussion purposes):
interface Variable {
someMethod: () => void
}
const validateVariable(variable: Variable | undefined) {
if(!variable) {
throw new Error('Variable is undefined!')
}
}
const doSomething = async (): void => {
// maybeGetSomething returns a Variable or undefined
// depending on the database, so both scenarios are possible
const variable: (Variable | undefined) = await maybeGetSomething()
validateVariable(variable)
variable.someMethod()
}
However, Typescript is throwing an error stating that variable
may be undefined. I find it impractical to include the code of validateVariable
within doSomething
as the validation process is complex and needs to be reusable. Creating a new variable just to appease Typescript seems unnecessary since after validation, the variable will always be of type Variable (as it cannot pass through the line with validateVariable(variable)
unless it meets the required conditions).
How can I approach this situation in a more efficient manner? I am open to restructuring my code, as I am still learning about Typescript and willing to adapt!