如何为react-pose中的Props定义TypeScript类型?(Props隐式为any)
Let's break down why you're hitting this error and how to fix it. The core issue is that TypeScript can't automatically infer the type of props inside your pose configuration callbacks, even when you've added a generic to posed.div or wrapped a typed component. Here's what you're missing:
1. First, Ensure You Have React-Pose Type Definitions
Before anything else, make sure you've installed the official TypeScript types for react-pose. Without these, TypeScript can't properly understand the types exposed by the library:
npm install --save-dev @types/react-pose # or yarn add -D @types/react-pose
2. Define a Complete Props Interface
Create a clear interface for your component's props that includes both your custom properties and the default props of a <div> element (like children, className, etc.). This avoids type errors when using standard div attributes:
import React from 'react'; import posed from 'react-pose'; interface FadeInProps extends React.HTMLProps<HTMLDivElement> { duration: number; hiddenOffset: number; }
3. Explicitly Type Props in Pose Callbacks
The generic you added to posed.div or your wrapped component doesn't automatically propagate to the callback functions in your pose configuration. You need to explicitly type the props parameter in each callback where you reference your custom properties:
Fix for Your First Approach (Directly Using posed.div)
const FadeIn = posed.div<FadeInProps>({ visible: { opacity: 1, scale: 1, x: 0, y: 0, transition: { // Explicitly type props here duration: (props: FadeInProps) => props.duration } }, hidden: { opacity: 0, scale: 0.8, // And here x: (props: FadeInProps) => props.hiddenOffset, y: 10 } });
Fix for Your Second Approach (Wrapped Component)
If you prefer using a custom component wrapper, the fix is similar—just ensure you type the props in the pose callbacks:
const FadeInContainer: React.FC<FadeInProps> = props => { return <div {...props} />; }; const FadeIn = posed(FadeInContainer)({ visible: { opacity: 1, scale: 1, x: 0, y: 0, transition: { duration: (props: FadeInProps) => props.duration } }, hidden: { opacity: 0, scale: 0.8, x: (props: FadeInProps) => props.hiddenOffset, y: 10 } });
Why This Works
By explicitly typing the props parameter in each callback, you're telling TypeScript exactly what shape the props should have, eliminating the implicit any type error. The FadeInProps interface ensures you get type checking for both your custom properties and standard div attributes, making your component more robust.
内容的提问来源于stack exchange,提问作者Kevin Brock

