最终将打字稿转换为javascript时,打字稿有什么用?

时间:2019-05-26 19:22:50

标签: javascript typescript

我读到打字稿引入了分配变量“类型”的概念,这样我们就可以避免在运行时出现类型错误。

我尝试在VS_CODE中实现“类型”概念。

这是我尝试过的代码

//main.ts

let message = "Hello all of you!!"

console.log(message);

let message2 : string = "Welcome typescript with the concept of 
'type' ";

console.log(message2);

message2 = 233;

console.log(message2);

这是我在控制台中遇到的错误。

main.ts:9:1 - error TS2322: Type '233' is not assignable to type 
'string'.

9 message2 = 233;

[00:30:56] Found 1 error. Watching for file changes.

已编译的JS代码

//main.js
"use strict";
var message = "Hello all of you!!";
console.log(message);
var message2 = "Welcome typescript with the concept of 'type' ";
console.log(message2);
message2 = 233;
console.log(message2);

JS输出

venkat-6805:Typescript-basics venkat-6805$ node main
Hello all of you!!
Welcome typescript with the concept of 'type' 
venkat-6805:Typescript-basics venkat-6805$ node main
Hello all of you!!
Welcome typescript with the concept of 'type' 
233
venkat-6805:Typescript-basics venkat-6805$ ;

所以我的问题是

  1. 打字稿发现错误后是否会停止翻译?

  2. 最终,每个打字稿代码都转换为JS代码。那打字稿有什么用?

1 个答案:

答案 0 :(得分:1)

  

1)发现错误时,打字稿不会停止翻译

如果要防止在发生此类错误时转换Typescript,则应在noEmitOnError中将true设置为tsconfig.json,例如:

{
  "compilerOptions": {
    "noEmitOnError": true
  }
}

否则,键入错误不会阻止代码被编译。

  

2)最终,每个打字稿代码都转换为JS代码。那打字稿有什么用

因为修复编译时错误相对容易,但是修复运行时错误则要困难得多。在一个特别糟糕的情况下,考虑一段很少运行的代码,您忘记在使用+之前将字符串转换为数字了。因此,不是someVariable + 5导致数字加上5,而是导致 string 得到5 concatenated ,这是意外的,并可能最终导致错误。如果最终导致错误,则可能很难找到错误的最终来源。在大型代码库中,这可能会浪费大量的程序员时间,特别是如果编写原始代码的人不是一个调试者。

使用Typescript时,当您尝试使用需要数字的字符串时,这种罕见的运行时错误会变成编译时错误。这是一个简单的5秒修复程序,这是一个很大的改进。

当然,Typescript还有其他基于意见的优缺点(需要花一些时间来学习,并且每个从事代码工作的人都必须知道使用它的方法),但这是保留的一种优势。头脑。