Skip to content

'in' expression should be a type guard #1427

Closed
@JsonFreeman

Description

@JsonFreeman

The in operator provides an opportunity for us to narrow a type. There are two ways that this could work:

  1. We can select particular constituents of a union type based on which members are present:
interface I1 {
    p: string;
}
interface I2 {
    q: string;
}

var v: I1 | I2;
if ("p" in v) {
    v.p; // Error
}
  1. If we have a general type like Object, we can clone the type and add a specific property to it when narrowing:
var v: Object;
if ("p" in v) {
    v.p; // Type should be { p: any }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already createdSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions