我找到了可能的答案:
Is any JavaScript code a valid TypeScript code?.
我正在使用Visual Studio和TypeScript插件进行Web项目.在以下帖子中,我找到了这个答案:
Not any valid JavaScript code is valid TypeScript see my example below.
var testVar = 4; testVar = "asdf";
TypeScript gives the following
error: Cannot convert string to number. To make that work in
TypeScript add “:any” like below.
var testVar: any = 4; testVar = "asdf"
This happens because TypeScript
noticed testVar is declared and in the declaration it is assigned a
number and therefore it decides it should stay a number.
我正在尝试使用HighCharts.如果我将代码保存在Javascript文件中,则不会出现任何错误.但是,当我将代码保存在Typescript文件中时,出现错误:
“Cannot find name “HighCharts”.
在这里,您可以看到我的代码的相关部分:
// Put definitions of highcharts, highstocks below this line
// Example 1 Chart
var initializeChart1 = function () {
require(['jquery', 'highcharts', 'highchartsMore', 'highchartsExporting'], function ($) {
$("#myChart").highcharts({
chart: {
type: 'spline',
backgroundColor: '#ECECEC',
// ------THIS GIVES AN ERROR, BUT WORKING WHEN SAVED AS .JS file
animation: Highcharts.svg, // don't animate in old IE
// -------------------------
...
我想将我的JavaScript代码保留在TS文件中的原因很简单:我目前正在学习TypeScript,并且我将JavaScript和TypeScript版本或相同的代码保留在同一文件中.根据TypeScript是否完成/正常工作,我将其取消注释并注释JavaScript.
我的问题是:
>为什么会出现此错误?
>是否可以使用任何JavaScript代码
在TS文件中?
解决方法:
是的,您可以在打字稿文件中使用js代码,但是编译器需要了解您使用的对象和库.
您可以通过两种方法进行编译.为您的库添加.d.ts文件,或者为了欺骗编译器,您可以这样声明自己的Highcharts对象.
declare var Highcharts: any;
var initializeChart1 = function () {
require(['jquery', 'highcharts', 'highchartsMore', 'highchartsExporting'], function ($) {
$("#myChart").highcharts({
chart: {
type: 'spline',
backgroundColor: '#ECECEC',
animation: Highcharts.svg, // don't animate in old IE
原文地址:https://codeday.me/bug/20191027/1944038.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。