0

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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for this - i didn't really know how to phrase the question to search the docs
@JaredSmith or @Federkun to avoid another duplicate question - using guard makes the type never in the else is there a way to annotate that? typescriptlang.org/play?#code/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.