我实现了一个React的高阶组件,作用是接收HTML标签原生属性,将被包装组件的props和标签属性分离然后传给被包装组件,在我定义baseProps时有一个ts错误,这是什么原因造成的,请各位解惑。
import React from "react";
export type FC<P = {}, El = HTMLDivElement> = React.FC<
P & {
htmlProps?: React.HTMLAttributes<El>;
}
> & {
props?: string[];
};
const withAttrs = <Props, El = HTMLDivElement>(Weiget: FC<Props, El>) => {
type pureProps = Omit<Props, "htmlProps">;
const WeigetWithAttrs: React.FC<pureProps & React.HTMLAttributes<El>> = (
props
) => {
let baseProps: Props = {};
let htmlProps: React.HTMLAttributes<El> = {};
let keys = Object.keys(props);
let propNames = Weiget.props || [];
keys.forEach((key) => {
if (key !== "chilren") {
if (propNames.includes(key)) {
baseProps[key] = props[key];
} else {
htmlProps[key] = props[key];
}
}
});
return (
<Weiget {...baseProps} htmlProps={htmlProps}>
{props.children}
</Weiget>
);
};
return WeigetWithAttrs;
};
export default withAttrs;
这里的 Props 是调用方指定的泛型类型,在实现方(即你这段代码)中并不知道 Props 究竟是什么类型。
比如你泛型传入的要是 “
{ mykey: '123' }
”,那这就等于 “let baseProps: { mykey: string } = {};
” 当然就会报错了。所以其实你应该写的是:
这样 TS 才能确保下面取值、赋值操作都能是类型安全的。
非要想像你这么写的话就断言吧: