Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
503 views
in Technique[技术] by (71.8m points)

requirejs - How use an external non-typescript library from typescript without .d.ts?

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>

Then in test.js:

 var myTree = Tree.tree({})

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

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

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...