【发布时间】: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<T,T> {、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