Skip to content

Type guard function prevents further type guarding #34798

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
ArmorDarks opened this issue Oct 29, 2019 · 2 comments
Closed

Type guard function prevents further type guarding #34798

ArmorDarks opened this issue Oct 29, 2019 · 2 comments

Comments

@ArmorDarks
Copy link

TypeScript Version: 3.6.3

Search Terms: user type guard function nested guarding

Code

type Test = TestOne | TestTwo;

interface TestOne  {
    type: 'one'
}

interface TestTwo {
    type: 'two'
}

const isTest = (data: unknown): data is Test => true

declare var payload: any

if (isTest(payload)) {
    if (payload.type === 'two') {
        // expected to be `TestTwo`, doesn't work
        payload
    }
}

const castedPayload = payload as Test

if (castedPayload.type === 'two') {
    // expected to be `TestTwo`, suddenly works
    castedPayload
}

Expected behavior:

Test should be type guarded and become TestTwo inside the if statement.

Actual behavior:

Test is not type guarded after the check. It remains Test.

Strangely enough, if payload is manually cast with as to be Test, type guarding suddenly works.

So, it seems to be tighed some how to the user type guard function isTest.

Playground Link: link

Related Issues:

Similar to the #26729, but not the same

@jack-williams
Copy link
Collaborator

Duplicate of #30557

@jack-williams jack-williams marked this as a duplicate of #30557 Oct 29, 2019
@ArmorDarks
Copy link
Author

@jack-williams Thanks! Closing this, as it's the same issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants