Skip to content

noImplicitReturns control flow errors with explicit type guard checks #23271

Closed
@tomrav

Description

@tomrav

TypeScript Version: 2.8.1 & 2.9.0-dev.20180409

Search Terms: noImplicitReturns throw type guard

Code

interface A { type: 'A' }
interface B { type: 'B' }

function isA(val: any): val is A { return val && val.type === 'A'}
function isB(val: any): val is B { return val && val.type === 'B'}

function getAOrThrow(val: A | B): A {
    if (isA(val)) { 
        return val; // val inferred to A
    } else if (isB(val)){ // val inferred to B
        throw new Error(); 
    }
    val // type inferred to never
}

Expected behavior:
Type check should pass without error.

Actual behavior:
Happens only with noImplicitReturns turned on.
getAOrThrow errors on its return value with Function lacks ending return statement and return type does not include 'undefined'..
If I remove the second type guard call (isB) and just leave it as a catch-all else, there is no error.

Playground Link:
Cannot reproduce in playground due to noImplicitReturns being turned off.

Related Issues:
Couldn't find any.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions