Typescript 是否支持使用 JavaScript 库的现有项目?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16866244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:49:17  来源:igfitidea点击:

Will Typescript support existing projects with JavaScript libraries?

typescript

提问by vish.Net

I would like to start using TypeScript in an existing project, but there are already a number of shared JavaScript libraries that I need to use in a TypeScript file. Is there any way for TypeScript to refer to those existing JavaScript libraries with project-related code?

我想开始在现有项目中使用 TypeScript,但已经有许多共享 JavaScript 库需要在 TypeScript 文件中使用。TypeScript 有没有办法用项目相关的代码来引用那些现有的 JavaScript 库?

I also tried porting the existing JavaScript libraries to TypeScript and I am getting a lot of compile time errors. It's tough to remove all the compile time errors. Why can't TypeScript just refer those JavaScript classes with a "suppress error and warning" option like Google Dart compiler?

我还尝试将现有的 JavaScript 库移植到 TypeScript,但遇到了很多编译时错误。删除所有编译时错误是很困难的。为什么 TypeScript 不能像 Google Dart 编译器那样只引用那些带有“抑制错误和警告”选项的 JavaScript 类?

采纳答案by vish.Net

Thanks for all your comments. I got the perfect answer in the below link

谢谢你们的评论。我在下面的链接中得到了完美的答案

How to slowly move to / migrate to TypeScript in an existing JavaScript system

如何在现有的 JavaScript 系统中慢慢迁移到/迁移到 TypeScript

回答by basarat

There are two cases here:

这里有两种情况:

  1. You are calling JavaScript from TypeScript
  1. 您正在从 TypeScript 调用 JavaScript

In this regard TypeScript works much like the google closure compiler. Everything needs to be declared before it can be used.

在这方面,TypeScript 的工作方式很像 google 闭包编译器。一切都需要声明才能使用。

So if you have a separate JavaScript file that has a variable Foo (class, module, number etc), you need to tell TypeScript about it. At its most basic case, you can do something like:

所以如果你有一个单独的 JavaScript 文件,它有一个变量 Foo(类、模块、数字等),你需要告诉 TypeScript。在最基本的情况下,您可以执行以下操作:

declare var Foo: any;

Otherwise you will get compile errors.

否则你会得到编译错误。

Later on you can build on this declaration. For third party libraries there is a huge resource available at https://github.com/DefinitelyTyped/DefinitelyTyped

稍后您可以在此声明的基础上进行构建。对于第三方库,https://github.com/DefinitelyTyped/DefinitelyTyped提供了大量资源

  1. Copying your JavaScript into TypeScript
  1. 将你的 JavaScript 复制到 TypeScript

An additional thing that might give compile errors is copying over your JavaScript to your TypeScript files. Here TypeScript will help you capture type errors like:

另一个可能会导致编译错误的事情是将 JavaScript 复制到 TypeScript 文件中。在这里,TypeScript 将帮助您捕获类型错误,例如:

var x = '123';
var y = x.toPrecision(4); // Error x is string not a number