Why should I bother using TypeScript if it ultimately gets converted into JavaScript?

I recently discovered that typescript introduces a concept called "type" to help avoid type errors during runtime.

Excited, I decided to implement this new concept in my code using VS_CODE.

Here is the snippet of code I experimented with:

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

Upon running the code, an error appeared in the console:

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.

Next, I examined the transpiled JS Code:

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

The resulting JS Output displayed:

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$ ;

This led me to ponder two questions:

  1. Will typescript halt transpilation when it encounters an error?

  2. Ultimately, since every typescript code is converted into JS code, what exactly is the purpose of typescript?

Answer №1

Does Typescript halt transpilation when it encounters an error?

To prevent Typescript from continuing transpilation in the presence of errors, you can enable the noEmitOnError option in your tsconfig.json file:

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

If this setting is not enabled, typing errors may not stop the code from being transpiled.

Even though all typescript code is eventually converted to JS, what is the purpose of using typescript?

The benefit of using Typescript lies in its ability to catch compile-time errors before they manifest as runtime issues. Consider a scenario where a string is mistakenly used instead of a number in a calculation - if left unchecked, this could result in unexpected bugs down the line. With Typescript, such errors are caught during compilation, making them easy to fix and preventing potential runtime issues.

In addition to this advantage, there are other factors to consider when deciding whether to use Typescript, such as the learning curve and the need for everyone working on the codebase to be familiar with it. However, the prevention of subtle runtime errors through compile-time checks is a key advantage of using Typescript.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to display data from the Nuxt.js store?

I am new to Nuxt JS and following a tutorial on the Nuxt website. I created a store in store/index.js. export const state = () => ({ mountain: [], }) export const mutations = { addMountain(state, mountain) { state.mountain.push(mountain) }, } ...

Preventing pop-up windows from appearing when triggered by a mouse click event

I am looking for a solution to trigger a popup window when a user right-clicks on a specific area. Here is the current code I am using: $("#popup").bind('mousedown', function(e) { var w; if(e.which==3) { w=window.open('link& ...

Is it possible to transfer the setState function between different contextProviders?

I'm encountering difficulties in setting a state when passing the context provider to other elements. Here is my code snippet. I have created a FancyboxContext so that I can easily access it from anywhere in the app. import React, { createContext, use ...

choosing anchor elements based on particular class names

I'm trying to use JavaScript to select a specific anchor in the menu, which is represented by a small image. When I click on this anchor, it should change the background to highlight the menu. I've successfully managed the class change using doc ...

A guide on simulating childprocess.exec in TypeScript

export function executeCommandPromise(file: string, command: string) { return new Promise((resolve, reject) => { exec(command, { cwd: `${file}` }, (error: ExecException | null, stdout: string, stderr: string) => { if (error) { con ...

In my React application, I have integrated p5 sketches that constantly loop and repeat

Currently facing a challenge integrating p5 sketches into my React App. I've tried adjusting the z Index of the toolbar to place the p5 elements underneath, but they end up repeating instead. Check out the repository here (sketches can be found in the ...

Differentiating between TypeScript string literal types and enums

Is it better to use enum or string literal type in TypeScript? String literal type: export type Animal = { id : number, name : string, type : "dog" | "cat" } Enum: export enum Type{ dog = "dog", cat = &qu ...

Implementing a JavaScript function to trigger the 'GET' method upon page load repeatedly

I am facing a strange issue where a javascript function is running multiple times upon page load (7 times in Chrome, 3 times in IE, 7 times in Firefox, 6 times in Opera, 4 times in Safari, and 4 times in Edge). What's going on??? Moreover, the xmlHtt ...

Experiment with parsing multiple outputs instead of repeatedly coding them as constants in Node.js

In my application, I am parsing multiple database data using cron and currently, I have it set up to create a const run for each data to find the dag_id and manually test the determineCron function one at a time. How can I create an array so that the "dete ...

Storing various text inputs in a MySQL database

Could anyone please assist me with fixing an issue I'm having with inserting data into a database from the form provided below? Unfortunately, I am unable to get it to work as expected. Here is the complete form: <html> <head> <m ...

``Is it possible to iterate through a collection of objects using a loop?

I am facing an issue with updating a global array that contains objects, where each object includes another array. My goal is to update the main array with values from the arrays within the objects following a specific logic! generalArray = [{name:String, ...

What is the best way to incorporate styled components and interpolations using emotion theming?

I've been building a React web application with a dynamic theme feature using the emotion-theming library. This allows users to switch between different environments, each with its own unique theme. To achieve this, I created my own CustomThemeProvide ...

The seamless operation of WordPress is disrupted upon the installation of a custom plugin

After creating a Vue plugin for WordPress, I encountered an issue where the plugin appears fine but when trying to add a new page, it displays a blank page. Disabling the plugin resolves the issue. Below is the code used for enqueuing the plugin: <?php ...

What are the steps to access a query parameter within an API route.js file using the latest App routing strategy?

Here is the goal I am aiming for: Utilize Next.js with App router. Establish a backend route /api/prompt?search=[search_text] Retrieve and interpret the search query parameter in my route.ts file. Based on the search parameter, send back data to the front ...

Issue: Formcontrolname attribute is undefined causing TypeError when trying to retrieve 'get' property.Remember to define formcontrolname attribute to

Having trouble creating a form at the moment and keep encountering this error: 'ERROR TypeError: Cannot read property 'get' of undefined' Even after trying various solutions like using formControlName in brackets or accessing the va ...

What is the best approach for creating a test case for a bootstrap-vue modal component

Exploring ways to effectively test the bootstrap vue modal display function. On the project page, the modal toggles its visibility using the toggleModal method triggered by a button click. The modal's display style is switched between 'none' ...

What purpose does the div tagged with the class selection_bubble_root serve in Nextjs react?

Just starting out with Nextjs and setting up a new Next.js React project. I used create-next-app to initialize the code base, but then noticed an odd div tag with the class 'selection_bubble_root' right inside the body. Even though its visibility ...

The jQuery AJAX function successfully executes, but the MySQL post deletion operation fails to take place

I am encountering an issue with this particular code. The Ajax code runs through to the end and then fades out the parent of the delete button. Below is the code for the delete button, post, and Ajax: <?php include('php/connect.php'); ...

Creating a User Authentication System using Node.js and Express

I am currently working on developing an application with node.js and expressJs, even though I come from a PHP background. In PHP, we typically use the session to handle logins, so naturally, I thought that in the case of node.js it would be similar. After ...

What could be the reason for the hr tag's CSS not appearing in React code?

In my React code, I am trying to create a border using the following code: <hr className="borderLine" /> However, when I attempt to style it with CSS, I utilize this snippet of code: .divider { margin: 2rem; width: 100%; color: ...