2016-02-05 149 views
3

我找到了一個可能的答案來解決我的問題: Is any JavaScript code a valid TypeScript code?TypeScript文件中的JavaScript代碼.ts不起作用

我正在使用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文件中,我不會收到任何錯誤。但是,當我保存打字稿文件中的代碼,我有一個錯誤:

"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。

我的問題是:

  1. 爲什麼我得到這個錯誤?
  2. 是否可以在TS文件中使用任何JavaScript代碼 ?
+0

您是否添加了對d.ts文件的引用? https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/highcharts-ng和https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/highcharts/highcharts.d.ts – Jerome2606

+1

我通過添加在require(['jquery','highcharts','highchartsMore','highchartsExporting'),函數($,Highcharts){}中的「Highcharts」引用。但我仍然困惑爲什麼這個代碼在保存時沒有這個引用就可以工作。 js文件但保存爲.ts文件時無法正常工作... – Marek

+1

引用僅僅是爲了幫助您以強有力的方式編寫代碼,並且需要打印腳本來指出可能出現的運行時錯誤。是爲了讓IDE在鍵入代碼時提供更豐富的環境來查找常見錯誤。檢查此答案以獲得打印機的簡單好點子http://stackoverflow.com/questions/12694530/what-is-typescript-and-爲什麼我會使用它在位的javascript – Jerome2606

回答

4

是的,您可以在打字稿文件中使用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 
+0

仍然需要用'requirejs'來做到這一點 – shotor