Skip to content

Allow comparing anything with null or undefined even when strict null checks are enabled #8439

Closed
@malibuzios

Description

@malibuzios

TypeScript Version:

1.9.0-dev.20160503

Code:

export function safeLibraryFunction1(arg: string) {
    if (arg == null)
        throw new TypeError(`Hi JS Consumer, I checked, it turns out the argument you 
                             gave was a null or undefined`);

    if (typeof arg !== "string")
        throw new TypeError(`Hi JS Consumer, I checked, the argument you gave me wasn't a string.. 
                             seems like something went wrong in your program?..`);
    // ..
}

interface SomeType {
    a: number;
}

export function safeLibraryFunction2(arg: SomeType) {
    if (arg === undefined)
        throw new TypeError(`Hi TS Consumer, it turns out the argument was undefined.
                             I don't assume you're using strict nullability checks,
                             I know that could be a bit difficult thing to introduce
                             or you haven't even heard about it 
                             so I also check at runtime :)`);
    if (arg === null)
        throw new TypeError(`Hi TS Consumer, it turns out the argument was null, 
                             maybe you had an unsafe cast somewhere in your program
                             or you're not using strict nullability checks?
                             I already thought of that so I checked anyway ;)`);
    // ..
}

export function safeLibraryFunction3(arg: SomeType) {
    if (arg != null) {
        //.. do something
    }
    else {
        throw new TypeError(`Hi JS Consumer, I think about you all the time
                             that's why I put many safeguards in my program
                             to make sure that everything goes smoothly..
                             c'ya later..`);
    }

}

Expected behavior:
The comparisons work.

Actual behavior:

Operator `==` cannot be applied to type X and null
Operator `===` cannot be applied to type X and null
Operator `===` cannot be applied to type X and undefined
Operator `!=` cannot be applied to type X and null

(My projects are full of these errors when strictNullChecks is enabled)

Metadata

Metadata

Assignees

Labels

CommittedThe team has roadmapped this issueFixedA PR has been merged for this issueSuggestionAn idea for TypeScript

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions