Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type guard on Number.isInteger is too strong #14

Closed
ehoogeveen-medweb opened this issue Jul 4, 2022 · 1 comment
Closed

Type guard on Number.isInteger is too strong #14

ehoogeveen-medweb opened this issue Jul 4, 2022 · 1 comment
Labels
bug Something isn't working

Comments

@ehoogeveen-medweb
Copy link

I was reading the discussion at microsoft/TypeScript#15048 and noticed that the definition of Number.isInteger from this library has the mentioned type guard, number is number.

To summarize the problem: When Number.isInteger returns false, the passed value may still be a number (just not an integer).

Unfortunately as that discussion shows there is currently no good way to represent this kind of 'weak type guard' in TypeScript, although microsoft/TypeScript#15048 (comment) does present an interesting workaround.

Adapted from that comment, you could do something like the following:

declare const container: unique symbol;
type SubtypeOf<T> = T & { [container]: T };

interface NumberConstructor {
  isInteger<T>(number: T): number is number & SubtypeOf<T>;
}

function test(n: unknown) {
  if (typeof n === "string" || typeof n === "number") {
    const a = n; // string | number

    if (Number.isInteger(n)) {
      const b: number = n; // number & { [container]: string | number }
    } else {
      const e = n; // string | number
    }
  }
}

Although the truthy branch has an awkward type for n, the assignment to b is valid (and the falsy branch maintains the unconstrained type).

I don't know what the best solution is here - remove the type guard, apply the workaround, or leave the type guard in place. The current type guard is technically unsafe though.

@uhyo uhyo added the bug Something isn't working label Jul 5, 2022
@uhyo uhyo closed this as completed in 3dd4dbd Dec 5, 2022
@uhyo
Copy link
Owner

uhyo commented Dec 7, 2022

Thank you, this is fixed in v2.2.0 by removing the type guards.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants