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

    Not a DefectThis behavior is one of several equally-correct options

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions