You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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:
declareconstcontainer: unique symbol;typeSubtypeOf<T>=T&{[container]: T};interfaceNumberConstructor{isInteger<T>(number: T): number is number&SubtypeOf<T>;}functiontest(n: unknown){if(typeofn==="string"||typeofn==="number"){consta=n;// string | numberif(Number.isInteger(n)){constb: number=n;// number & { [container]: string | number }}else{conste=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.
The text was updated successfully, but these errors were encountered:
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
returnsfalse
, the passed value may still be anumber
(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:
Although the truthy branch has an awkward type for
n
, the assignment tob
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.
The text was updated successfully, but these errors were encountered: