Skip to content

Typescript should warn when checking for null or undefined on non-nullable type #17896

@wizarrc

Description

@wizarrc

Proposal: Add an error or warning when strictNullCheck is turned on and a null check is applied to a non-null type.

Motivation: The developer is often times converting a code base that does not originally have strict null checking turned on. After turning it on, bugs are often revealed and require refactoring, moving where the types are null and not null in the code. When refactoring, it is often times difficult to spot redundancy in null checks. By informing the user with an error or warning, it allows the developer to easily spot where their logic is flawed.

TypeScript Version: 2.4.0

Code

function normalizeName(name: string): string {
    if(name === undefined) return ''; // Should warn that this is unnessary and suggest removing or adding ` | undefined` to name type
    if(name.length === 0) return name;
    return name[0].toUpperCase() + name.substr(1);
}

function alertName(name: string | undefined) {
    alert(normalizeName(name!));
}

(function () {
    alertName(undefined);
}());

Expected behavior:

This should give warning that null check is not needed or should be moved outside the inner function. This would allow me to spot where my error is and remove the ! operator with code like this:

function normalizeName(name: string): string {
    if(name.length === 0) return name;
    return name[0].toUpperCase() + name.substr(1);
}

function alertName(name: string | undefined) {
    alert(name === undefined ? '' : normalizeName(name));
}

(function () {
    alertName(undefined);
}());

Obviously this is a very simple example to demonstrate my point, but this can get much more challenging with a very large and deeply nested code base.

Actual behavior:

No warning or error is displayed.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions