「TypeScript」请问为什么泛型在函数中作为变量类型会报错

新手上路,请多包涵

我实现了一个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;
阅读 1.1k
1 个回答

这里的 Props 是调用方指定的泛型类型,在实现方(即你这段代码)中并不知道 Props 究竟是什么类型。

比如你泛型传入的要是 “{ mykey: '123' }”,那这就等于 “let baseProps: { mykey: string } = {};” 当然就会报错了。

所以其实你应该写的是:

let baseProps: Partial<Props> = {};

这样 TS 才能确保下面取值、赋值操作都能是类型安全的。

非要想像你这么写的话就断言吧:

let baseProps: Props = {} as Props;
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题