Is any JavaScript code a valid TypeScript code?

前端 未结 2 1150
情深已故
情深已故 2020-11-30 13:52

Currently I\'ve started to learn TypeScript. From the documents I\'ve studied for TypeScript, I saw some samples that pure JavaScript

2条回答
  •  借酒劲吻你
    2020-11-30 14:13

    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.

提交回复
热议问题