3 ms·
Funny. Seems I fell into the same trap I just sketched, making wrong assumptions because of not looking around in the code. But to be honest from your explanati
by stinos 3y ago
Funny. Seems I fell into the same trap I just sketched, making wrong assumptions because of not looking around in the code. But to be honest from your explanation I still cannot tell whether I merely used incorrect terminology wrt dynamic typing (but the general principle still holding) or whether this code guarantees that defaultValue is in fact always a numeric type?
- cxr 3y agoThis code doesn't. It guarantees that within `useControlledState`[1], `defaultValue` is either NaN, an actual number, a number-like string, or something else that can be coerced into one[2]. If `defaultValue` is, for example, `true` or even an empty array, then the result of the expression `isNaN(defaultValue) ? NaN : defaultValue` will pass through `true` or the empty array. 1. <https://github.com/adobe/react-spectrum/blob/main/packages/%40react-stately/utils/src/useControlledState.ts https://github.com/adobe/react-spectrum/blob/main/packages/%...> 2. whether one of those non-numbers is prevented from actually making an appearance at this point for other _reasons_ is a different question, but the fact remains that one making its way through is not something that would be stopped from proceeding further by the isNaN check here (Addendum to, I hope, clarify: I'll reiterate that it's the type annotations on the `useControlledState` call site parameterized as `useControlledState<number>` (and the TypeScript team's decision to type `isNaN` to take only parameters with a number type) that "guarantees" `defaultValue` is a number. But that guarantee is a soft one, i.e. not a guarantee at all, precisely because of mobile code and separate compilation; I can contrive a project right now that uses the Adobe Spectrum library and pass whatever I want to it—it's not like the Adobe devs' compilers are going to be able to stop me.)
- deleted 3y ago[deleted]