我正在制作一个像缝线一样工作的库,您可以在其中使用类创建样式化组件:
import {styled} from 'my-package'
const Text = styled("div", "text-slate-700 font-sans");
我的问题是关于这个函数的类型推断。正如您所注意到的,它在第一个参数中接收一个字符串或一个组件,目的是获取在第一个参数中传递的组件的道具。
我可以用简单的对象复制我想要的东西:
type ComponentType =
| keyof JSX.IntrinsicElements
| React.ComponentType<any>;
const type: ComponentType = "div";
// It infer the types form the "div" string
type ComponentProps = React.ComponentPropsWithRef<typeof type>;
// Here it works !
const props: ComponentProps = {
onChange: (e) => console.log(e.target),
};
但是当我尝试使用
React.forwardRef
函数传递相同的东西时,道具以 any
类型出现:
type ComponentType =
| keyof JSX.IntrinsicElements
| React.ComponentType<any>;
function _styled(type: ComponentType) {
return React.forwardRef<
React.RefAttributes<typeof type>,
React.ComponentPropsWithRef<typeof type>
>((props, forwardedRef) => {
return React.createElement(type, { ...props, ref: forwardedRef });
});
}
如果您在下图中注意到,vscode 会告诉您道具的类型是
any