如何在没有 .d.ts 的情况下使用打字稿中的外部非打字稿库? [英] How use an external non-typescript library from typescript without .d.ts?

查看:28
本文介绍了如何在没有 .d.ts 的情况下使用打字稿中的外部非打字稿库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在我的 .html 文件中定义了这些:

I have defined these in my .html file:

<script type="text/javascript" src="bower_components/tree.js/tree.min.js"></script>
<script type="text/javascript" src="bower_components/q/q.js"></script>
<script type="text/javascript" src="test.js"></script>

然后在 test.js 中:

Then in test.js:

 var myTree = Tree.tree({})

但是打字稿出错说:找不到名字‘树’"

But Typescript errors out saying: "Cannot find name 'Tree'"

我也尝试使用 --module amd 编译并将 import Tree = require("model/tree"); 放在 test.js 文件的顶部,但它再次出错:Cannot find external module 'model/tree'. 但是很明显它应该是一个有效的导入,请参见此处定义它的位置:https://github.com/marmelab/tree.js/blob/master/src/main.js

I also tried compiling with --module amd and placing import Tree = require("model/tree"); at the top of the test.js file, but it errors out again: Cannot find external module 'model/tree'. however clearly it should be a valid import, see here where it was defined: https://github.com/marmelab/tree.js/blob/master/src/main.js

不想想为我想使用的每个外部 javascript 文件编写 .d.ts 文件,这真的是 Typescript 想让我做的吗?

I do not want to write .d.ts files for every single external javascript file I want to use, is that seriously what Typescript wants me to do?

推荐答案

我不想为我想使用的每个外部 javascript 文件编写 .d.ts 文件,Typescript 真的想让我这样做吗?

I do not want to write .d.ts files for every single external javascript file I want to use, is that seriously what Typescript wants me to do?

没有.最简单/最快的解决方案就是告诉它存在一些变量 Tree .这很简单:

No. The simplest / quickest solution is simply to tell it that there is some variable Tree out there. This is as simple as:

declare var Tree:any; // Magic
var myTree = Tree.tree({})

TypeSafety 是 TypeScript 中的一个滑动比例.在这种情况下,您只是告诉编译器有一个名为 Tree 的东西,您将对其进行管理,除了 它存在这一事实之外,并不关心太多类型安全.

TypeSafety is a sliding scale in TypeScript. In this case you are only telling the compiler that there is something called Tree that you will manage and don't care for much typesafety beyond the fact that it is there.

恕我直言:declare var Tree:any; 行比其他 JS 验证工具的语法要简单得多,您需要编写这些工具来声明对代码中不存在的变量的使用.

IMHO: The line declare var Tree:any; is much simpler syntax than other JS veficiation tools would have you write to declare your usage of variables that are not present in your code.

interface ITree {
    .. further methods and properties...
}

interface ITreeFactory {
    tree(input: { [key: string]: any }): Itree
};

declare var Tree: ITreeFactory; // magic...

这篇关于如何在没有 .d.ts 的情况下使用打字稿中的外部非打字稿库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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