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
Currently the return type of valueOf is never. This is correct
as it will never return a value but always throw.
The issue is that never actually behaves a lot like any.
The never type is a subtype of, and assignable to, every type;
however, no type is a subtype of, or assignable to, never (except
never itself). Even any isn’t assignable to never.
constv=instant.valueOf()console.log(v+1)// no problem
It further means that the following snippet will not raise an error
at compile time (while it will at runtime).
I updated your playground example to also call valueOf() directly. Interestly, I couldn't reproduce the "unreachable code" error with the current version (can you link to an example of this?).
Here are my thoughts on the three options:
Making valueOf private seems promising, assuming it's reasonable to be a class. Obviously it's not possible for an interface.
Making valueOf optional seems somewhat unsatisfying. One possible consideration is that if subclasses are possible, then they can override an optional method with a required method (though it would still have to return never for covariance).
Note that never|x is the same as just x, since never is the union identity. So I don't think this is a good option - it's also the only option of the three that permits direct calls to valueOf without any complaint at all.
You are right there well. I meant to actually remove that suggestion. unknown or unique symbol would be the remaining options to at least prevent assignment and still making the value somewhat unusable.
edit: Updated issue summary to reflect above discussion.
Currently the return type of
valueOf
isnever
. This is correctas it will never return a value but always throw.
The issue is that
never
actually behaves a lot likeany
.It further means that the following snippet will not raise an error
at compile time (while it will at runtime).
A few options of what one could do to make TypeScript point out
the issue here:
valueOf
asprivate
,valueOf
optional,valueOf
returnunknown
,undefined
, or aunique symbol
.I added an exploration of these options in a playground.
The text was updated successfully, but these errors were encountered: