This might not be possible in typescript but it seems like the TS compiler should be able to figure this out some way. Example here
function validateFoo(val: string | undefined) {
return val !== undefined ? true : false
}
let myVal: string | undefined
if (validateFoo(myVal)) {
console.log("output: ", myVal.toLowerCase()) // Error: Object is possibly 'undefined'.
}
it seems like inside the if
statement that myVal must not be undefined. However typescript says it may be. Is there some way to annotate that function similar maybe to:
if (!myVal) {
throw new Error("myVal undefined")
}
console.log(myVal.toLowerCase())
would mark myVal
as defined after the throw.
That's what type guards does:
function validateFoo(val: string | undefined): val is string {
https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments