Skip to content

x is any type guard widens unknown type even after the relevant scope has been exited #63074

@coreywoodfield

Description

@coreywoodfield

🔎 Search Terms

any unknown type guard predicate

🕗 Version & Regression Information

This is the behavior in every version I tried, and I reviewed the FAQ for entries about not-bugs

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.9.3#code/GYVwdgxgLglg9mABDAzgQTATwBQA8Bci4A1mHAO5gCUhuyKiAhlogN4BQiXiATgKZQQPJFB4g+AbnYBfduwgIUUJoRJlKiALyIA5MDhwdU+YuUAjQmBABbM3x5amExAHoXiBdYAOMADb3Eex44BwBaRAAVTC8+XTUKMB16RDJlRhQUGABzMEYzf0QoOELo2J0rW3sdADp2GGBEbFQMHEYqKjZObgUwJQ9LGzsHbUYpWR6+gBMByuGnV3cyDzhvPwCgkIAaJkQAC3TEOz4kchhJ475JwuLmTHYgA

💻 Code

function isAny(x: unknown): x is any {
    return true;
}

const a: unknown = 'foo';

const b: number = a; // compiler error - Type 'unknown' is not assignable to type 'number'.
if (isAny(a)) {
    const c: number = a;
}
const d: number = a; // no compiler error, a has been widened to any

🙁 Actual behavior

if (isAny(a)) changes the type of a from unknown to any both within the if statement and after the if statement.

🙂 Expected behavior

type guards shouldn't change the type of a variable typed as unknown except within their scope

Additional information about the issue

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions