Reputation: 167
So I was using framer motion with Typescript and I was wondering if there is a way to make your variants typesafe so that you can get nice autocomplete and make fewer mistakes. I was also using the custom prop for custom data and would like to make that typesafe. here is an example snippet:
import { motion } from "framer-motion";
export default function App() {
const variants = {
initial: (x: number) => {
return {
x: x
};
},
final: {
x: 0,
transition: {
duration: 0.8
}
}
};
return (
<motion.div
className="App"
variants={variants}
custom={100}
initial="initial"
animate="final"
>
<h1>Framer Motion</h1>
<h2>Testing with typescript</h2>
</motion.div>
);
}
so what I want is that after defining my variants when I use them in my motion.div
it should provide autocompletion that the possible values for initial
prop are "initial" and "final" and also provide type safety with the custom value. Right now I have defined that the value of x should be a number but in the custom prop even if given an array or object it does not complain. I have tried to import Variants from framer motion and tried to use it like this const variants: Variants{}
but it doesn't seem to work. Please help me if I am doing this in the correct way or not.
Upvotes: 1
Views: 7388
Reputation: 51
With the retyping the initial prop you can create your custom motion div component which will extend the base type with yours
https://codesandbox.io/s/jovial-elion-xzt7g3
interface CustomMotionDivProps extends HTMLMotionProps<"div"> {
initial: "initial" | "final";
// any other thing
}
export default class CustomMotionDiv extends Component<CustomMotionDivProps> {
render() {
return <motion.div {...this.props}>{this.props.children}</motion.div>;
}
}
The other problem you have with the variants
I do not understand. If you want prop variants
of the motion.div to allow exact type, you can define it next to the initial
in the CustomMotionDiv.
Upvotes: 1