如何在没有. d.ts 的情况下使用来自类型脚本的外部非类型脚本库?

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

<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 中:

 var myTree = Tree.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

我想写作。对于每个我想要使用的外部 javascript 文件,这真的是 Type 脚本想要我做的吗?

63014 次浏览

You may define 'require' yourself and use undocumented amd-dependency feature of TypeScript:

/// <amd-dependency path="model/tree" />
declare var require:(moduleId:string) => any;
var Tree = require("model/tree");

'amd-dependency' directive will tell the compiler to include your module to "define" arguments in generated code: see a sample here.

You may also check a very good article which explains how to use TypeScript with RequireJS.

But note that without writing proper TypeScript definitions for your existing code you won't be provided with any type information, and so you won't get type safety checks, advanced code completion in tools and so on. So, your 'Tree' will actually be of type 'any', and actually will be a dynamic JS piece inside other TS code.

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?

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 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.

More

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.

Update

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


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


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