Skip to content

unknown type is narrowed to {} in strict equality condition since 4.8Β #50567

Description

@43081j

Bug Report

πŸ”Ž Search Terms

narrowing, object type, unknown, unknown narrowing

πŸ•— Version & Regression Information

  • This changed between versions 4.7.x and 4.8.x
  • Happens in nightly (4.9.x)

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

const foo = (value: unknown): string => {
    if (!value) {
        return 'foo';
    }
    if (value === 'xyz') {
        return value; // Type '{}' is not assignable to type 'string'.
    }
    return '';
};

// This one compiles fine
const bar = (value: unknown): string => {
    if (value === 'xyz') {
        return value;
    }
    return '';
};

πŸ™ Actual behavior

Type '{}' is not assignable to type 'string'.

Even though we've clearly inferred that the unknown is literally the string "xyz", the compiler somehow thinks it is instead {}.

πŸ™‚ Expected behavior

Builds fine.

More info

You can see here that its specific to having the false-check at the start of the function.

Removing the if(!value) condition causes the code to compile as expected.

So it seems that turns the value into {} somehow.

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFix AvailableA PR has been opened for this issue

Type

No type

Fields

No fields configured for issues without a type.

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions