【问题标题】:How to write Typescript Definition File for exiting JavaScript如何编写退出 JavaScript 的 Typescript 定义文件
【发布时间】:2016-09-11 09:54:28
【问题描述】:

我想使用 React 组件https://github.com/alexkuz/react-json-tree 这是在我的 typescript 项目中用 JavaScript 编写的。

用法按照Javascript中的例子很简单:

import JSONTree from 'react-json-tree'

// Inside a React component:
const json = {
  array: [1, 2, 3],
  bool: true,
  object: {
    foo: 'bar'
  }
}

<JSONTree data={json} />

只是为了让这个示例运行,我写道:

/// <reference path="../ambient/react/index.d.ts" />

declare namespace ReactJsonTree{
    interface JSONTreeProps{
        data: any;
    }

    class JSONTree extends __React.Component<JSONTreeProps, void>{}
}

declare module "react-json-tree" {
    export = ReactJsonTree;
}

编译现在可以工作了,但是将其用作

import {JSONTree} from "react-json-tree";
...
<JSONTree data={somedata} />

我收到运行时错误:

SCRIPT5022:元素类型无效:需要字符串(对于内置组件)或类/函数(对于复合组件),但得到:未定义。检查Index的渲染方法。

警告:React.createElement:类型不应为 null、未定义、布尔值或数字。它应该是一个字符串(对于 DOM 元素)或一个 ReactClass(对于复合组件)。检查Index的渲染方法。

我是为现有 JavaScript 库编写定义类型的新手。

那么谁能给我一个有用的建议?

【问题讨论】:

  • 我还需要一个 react-json-tree 的定义,并且我已经重新创建了您的错误消息。在开始之前,我想知道您是否取得了任何进展?

标签: reactjs webpack definitelytyped


【解决方案1】:

我能够复制您的错误消息。我认为您没有正确导出,导入时 JSONTree 未定义(由运行时错误消息暗示)。

我确实让它与this work-in-progress 定义一起工作:

declare namespace ReactJsonTree {

    interface JSONTreeProps{
        data: any;
        hideRoot?: boolean;
        invertTheme?: boolean;
        theme?: any | string;
    }

    class JSONTree extends React.Component<JSONTreeProps, any> {}
}

declare module "react-json-tree" {
    export default  ReactJsonTree.JSONTree;
}

因为它是一个default 导出,所以我像this 一样导入它:

import JSONTree from "react-json-tree";

// ...

<JSONTree data={this.props.logs} />

【讨论】:

    猜你喜欢
    • 2019-04-16
    • 2016-07-10
    • 2017-02-10
    • 2017-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-21
    • 1970-01-01
    相关资源
    最近更新 更多