8000 Type predicate results stored in variables don't narrow guarded types · Issue #22341 · microsoft/TypeScript · GitHub
[go: up one dir, main page]

Skip to content
Type predicate results stored in variables don't narrow guarded types #22341
Closed
@bgmort

Description

@bgmort

TypeScript Version: 2.8.0-dev.20180222

Search Terms:
assignable type guards
assignable type guard return value
assign type guard to variable

Code

interface A {
    type: 'A';
    aProperty: string;
}

interface B {
    type: 'B';
    bProperty: number;
}

type AorB = A | B;

function isA(obj: AorB): obj is A {
    return obj.type === 'A';
}

const o = { type: 'A', aProperty: 'value' } as any as AorB;

// this should be an error, and it is
console.log(o.aProperty);

// this should work, and it does
if (isA(o)) {
    console.log(o.aProperty);
}

// this example discards the type guard information, but it 
// ought to set oIsA to type (o is A), and apply the type
// guard inside the if statement. 
const oIsA = isA(o);
if (oIsA) {
    console.log(o.aProperty);
}

Expected behavior:
oIsA should have the type returned by the type guard function. if (oIsA) ... should narrow the type of o within the if block.

Actual behavior:
oIsA is a regular boolean value. The type guard function can only be used directly within a conditional block.

Playground Link:
https://goo.gl/6Pk5vr

Related Issues:

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

      0