Skip to content

Indirect type narrowing via const #12184

Closed
@gasi

Description

@gasi

TypeScript Version: 2.0.3

Code

interface Square {
    kind: "square";
    size: number;
}

interface Rectangle {
    kind: "rectangle";
    width: number;
    height: number;
}

type Shape = Square | Rectangle;

function area(s: Shape) {

    // // Doesn’t compile: Using a `const` as a type guard:
    // // `error TS2339: Property 'size' does not exist on type 'Shape'.`

    // const isSquare = s.kind === 'square';
    // if (isSquare) {
    //     return s.size * s.size;
    // }

    // // `s` is not narrowed to type `Rectangle`

    // Compiles: Directly using `s` in the type guard:
    if (s.kind === 'square') {
        return s.size * s.size; // `s` has type `Square`
    }

    // `s` is narrowed to type `Rectangle`

    return s.width * s.height;
}

Expected behavior:

s’s type can be narrowed indirectly via a const.

Actual behavior:

s’s type can only be narrowed via direct access.

Metadata

Metadata

Assignees

Labels

RevisitAn issue worth coming back toSuggestionAn idea for TypeScript

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions