motiondivision / motion

A modern animation library for React and JavaScript
https://motion.dev
MIT License
25.96k stars 851 forks source link

Require and return a numeric MotionValue in useSpring types #2702

Closed controversial closed 4 months ago

controversial commented 5 months ago

The current types for useSpring use MotionValue<any>, even though in practice useSpring only handles numeric MotionValues.

Since useSpring only accepts numeric inputs and only returns a numeric MotionValue, it should be typed with MotionValue<number> in order to be as specific as possible, and encourage as much type safety as possible.

It’s common for developers to enable linter rules that protect against unsafe uses of any values in TypeScript, since those values are prone to break type safety guarantees. The current types for useSpring create such “unsafe” types even though in practice, the value is always a number. See the following example:

Screenshot 2024-06-17 at 12 06 09 PM

Closes #2495

mattgperry commented 4 months ago

I sort of agree. I think the improved return type is great and we should keep that.

For the input MotionValue I'm sort of ambivalent. I agree that the example in the linked PR shouldn't be accepted but I do feel like as we support spring animations on values like "100px" or whatever that intuitively this should be accepted too:

const px = useMotionValue("100px")
useSpring(px)

Realistically we're gonna need to keep the input sanitised because it is quite potentially used within Framer user code. For now I'd prefer to leave the input types as-is too. But if this could be amended to improve only the return type then I can merge and publish.

controversial commented 4 months ago

Thanks for the feedback @mattgperry - I pushed another commit to address this case!

useSpring now accepts any MotionValue<unknown> as input, and type-safely transforms that input to a number, to return a MotionValue<number>

Sorry it took me a little while to get to this

mattgperry commented 4 months ago

Thanks for the updates, I'll merge and publish now!