Skip to content

Number.isInteger and others should accept any and act as type guards #21199

Closed
@cyco130

Description

@cyco130

TypeScript Version: 2.7.0-dev.20180116

Code

function ensureInt(x: number | string): number {
    if (Number.isInteger(x)) { // Same with isSafeInteger, isNan and isFinite
        return x;
    } else {
        throw Error("Type error");
    }
}

Expected behavior:
It should compile without errors.

Actual behavior:
The compiler complains as follow:

file.ts(2,26): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'.
  Type 'string' is not assignable to type 'number'.
file.ts(3,9): error TS2322: Type 'string | number' is not assignable to type 'number'.
  Type 'string' is not assignable to type 'number'.

Proposed solution:
Rewrite es6 type definition of NumberConstructor.isInteger (et al.) like this:

isInteger(number: any): number is number;

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