【问题标题】:How do I write a type definition for a a sub class (React.Component) in typescript?如何在打字稿中为子类(React.Component)编写类型定义?
【发布时间】:2018-06-26 22:24:24
【问题描述】:

我正在尝试弄清楚如何为 react-highlight(Highlightable 类,请参阅 here)编写类型定义,以便 扩展 Highlightable 并添加自定义功能。由于最初的 Highlightable JS 类是 React.Component 的子类,因此我还需要在我的类型定义中提供 React.Component 的所有方法。解决这个问题的最佳方法是什么?

这是使用 NPM 和 webpack。我正在关注this tutorial

我尝试像这样导入和使用组件:

import {Highlightable} from "highlightable";

然后:

<Highlightable
enabled={true}
highlightStyle={{
...

我的目标是能够说:

class MyHighlightable extends Highlightable { ...}

并覆盖方法。这就是我想要一个类型定义的原因。

通过将declare module "highlightable"; 添加到src/@types/highlightable 中的index.d.ts 文件,我设法让一个简单的导入工作。

当我现在尝试添加这样的类定义时:

 declare module "highlightable" {
   export class Highlightable {
   }
}

Typescript 当然会抱怨 React.Component 超类中缺少的方法:

TS2607: JSX element class does not support attributes 
because it does not have a 'props' property.

因此,当使用空类主体 export class Highlightable extends React.Component&lt;T,T&gt; {index.d.ts 进行扩展并添加方法定义等时,一切都会编译,但在运行时出现此错误:

Uncaught Error: Element type is invalid: expected a string (for 
built-in components) or a 
class/function (for composite components) but got: undefined.

将 Highlightable 导入输出到控制台确认它是未定义。 从 Definately typed 上的 React 类型定义复制和粘贴方法定义也无济于事(仍然 undefined)。

如何解决这个问题并为子类提供类型定义?如果不可能,我该如何解决?

【问题讨论】:

    标签: javascript reactjs typescript npm typescript-typings


    【解决方案1】:

    已解决,灵感来自 this post。我的类型定义现在看起来像这样:

    declare namespace HighlightableNs {
        class Highlightable extends React.Component<any, any> {
        }
    }
    
    declare module "highlightable" {
        export default HighlightableNs.Highlightable;
    }
    

    子类化时,我使用默认导入:

    import Highlightable from "highlightable";
    
    export class HighlightableColorMarked extends Highlightable {
    

    自定义类现在可以正常导入了:

    import {HighlightableColorMarked} from "./wordselection/HighlightableColorMarked";
    

    如果有人知道为什么这是必要的或有更优雅的解决方案,请随时发布。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-25
      • 2017-04-13
      • 2022-01-02
      • 2018-01-18
      • 1970-01-01
      • 1970-01-01
      • 2018-08-24
      • 1970-01-01
      相关资源
      最近更新 更多