Skip to content

narrowing to null via typeguards doesn't work #27634

Closed
@zpdDG4gta8XKpMCd

Description

@zpdDG4gta8XKpMCd

i am hacking my way around this limitation #11920

so my goal is to make sure that isNull only applied to T | null types and by this i mean that null must be a valid case of a given type (types that don't have | null must not be permitted), i am trying to use conditional types to enforce it, this is what i got

unfortunately it doesn't work and i am clueless what i am doing wrong, it looks like a bug

export function isNull<T extends (null extends T ? any : never)>(value: T | null): value is null {
    return value === null;
}

declare var x: null | number;
if (isNull(x)) { // <-- expect to work, actual: number is not assignable to null
}
declare var y: number;
if (isNull(y)) { // <-- expect a type error
}

@ahejlsberg you might want to look at it

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions