繁体   English   中英

如何在打字稿中扩展React.SFC类型

[英]how to extend React.SFC type in typescript

在反应类型中,我们发现以下内容:

type SFC<P = {}> = StatelessComponent<P>;
interface StatelessComponent<P = {}> {
    (props: P & { children?: ReactNode }, context?: any): ReactElement<any> | null;
    propTypes?: ValidationMap<P>;
    contextTypes?: ValidationMap<any>;
    defaultProps?: Partial<P>;
    displayName?: string;
}

我想用一个属性fragment来扩展它。 我已经在我的index.d.ts typings/react文件夹中创建了index.d.ts ,但无法弄清楚如何正确扩展类型,因此不会破坏其余的代码。 我已经尝试过类似的东西:

declare module "react" {
  import React, { SFC as ReactSFC} from "react";

  export type SFC<P = {}> = ReactSFC<P> & { fragment: any };

  export = React;
}

但它基本上破坏了JSX代码

有适当的方法吗?

谢谢

不能像这样覆盖类型别名。 而是在相同的模块名称下声明您自己的StatelessComponent接口,它将与原始接口合并。 这是正确的语法:

declare module "dummy" {
  module "react" {
    interface StatelessComponent<P = {}> {
      fragment?: any;
    }
  }
}

需要外部模块声明,以使内部模块声明成为“增强”,而不是如本线程中所述遮蔽原始模块。 不幸的是,该技巧没有正确记录AFAIK。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM