简体   繁体   中英

JavaScript code inside TypeScript file .ts not working

I found a possible answer to my question: Is any JavaScript code a valid TypeScript code? .

I am working on a web project with Visual Studio and TypeScript plugin. Inside the following post, I have found this answer:

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.

I am trying to use HighCharts. If I save the code inside Javascript file, I dont get any error. But when I save the code inside Typescript file, I have an error:

"Cannot find name "HighCharts".

Here you can see the relevant part of my code:

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

...

The reason why I want to keep my JavaScript code inside TS file is simple: I am currently learning TypeScript and I keep JavaScript and TypeScript versions or same code in same file. Depending on if TypeScript is complete/working, I uncomment it and comment JavaScript.

My questions are:

  1. Why I get this error?
  2. Is it possible to use any JavaScript code inside TS files?

Yes you can use js code in your typescript files but the compiler needs to know about the objects and libraries you use. You have two options to make this compile. Either add the .d.ts file for your library or to fool the compiler you can declare the Highcharts object yourself like this.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM