镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

noImplicitReturns control flow errors with explicit type guard checks #23271

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.

Activity

  1. tomrav commented on Apr 10, 2018

    @tomrav
    Author

    Seems similar to #23281

  2. tomrav commented on Apr 10, 2018

    @tomrav
    Author

    Thanks for the tip, didn't know you could do that! 👍

  3. mhegazy commented on Apr 10, 2018

    @mhegazy
    Contributor

    Please see #17358, #20409, #10470 and #9655

  4. tomrav commented on Apr 11, 2018

    @tomrav
    Author

    I see how you're approaching it now, I'll close the issue.
    Thanks 👍

  5. locked and limited conversation to collaborators on Jul 25, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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