如何编写用于退出 JavaScript 的 Typescript 定义文件 [英] How to write Typescript Definition File for exiting JavaScript

查看:27
本文介绍了如何编写用于退出 JavaScript 的 Typescript 定义文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 React 组件 https://github.com/alexkuz/react-json 树这是在我的打字稿项目中用 JavaScript 编写的.

I want to use the React component https://github.com/alexkuz/react-json-tree which was written in JavaScript in my typescript project.

用法根据Javascript中的示例非常简单:

The usage is according to the example very simple in 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} />

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

Only to get this sample running I wrote:

/// <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;
}

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

The compiliation now works but, using it as

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

我收到运行时错误:

SCRIPT5022:元素类型无效:应为字符串(对于内置组件)或类/函数(对于复合组件)但得到:未定义.检查Index的render方法.

SCRIPT5022: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. Check the render method of Index.

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

Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components). Check the render method of Index.

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

I am a new in writing defintion typings to existing JavaScript libraries.

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

So can anyone give me a helpful advice?

推荐答案

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

I was able to replicate your error message. I do not think you were exporting correctly, JSONTree is undefined when you import it (alluded to by the runtime error message).

我确实让它与 this 一起使用 在制品定义:

I did get it to work with this work-in-progress definition:

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 导出,我然后像 这个:

And since it is a default export I then import it like this:

import JSONTree from "react-json-tree";

// ...

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

这篇关于如何编写用于退出 JavaScript 的 Typescript 定义文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆