Skip to content

in Operator Narrowing is Too Limited #50891

Closed
@DanielRosenwasser

Description

@DanielRosenwasser

Playground Link

interface RGB {
    red: number;
    green: number;
    blue: number;
}

function setColor(value: unknown) {
    const isRGB =
        // is an object
        value && typeof value === "object" &&
        // 'red' exists and is a 'number'
        "red" in value && typeof value.red === "number" &&
        // 'green' exists and is a 'number'
        "green" in value && typeof value.green === "number" &&
        // 'blue' exists and is a 'number'
        "blue" in value && typeof value.blue === "number";

    if (isRGB) {
        const rgb: RGB = value;
    }
}

Expected: No errors
Actual Errors.

Type 'object & Record<"red", unknown> & Record<"green", unknown> & Record<"blue", unknown>' is not assignable to type 'RGB'.
  Types of property 'red' are incompatible.
    Type 'unknown' is not assignable to type 'number'.

Metadata

Metadata

Assignees

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