Into The Verse of Typescript 🎯

Into The Verse of Typescript 🎯

Β·

6 min read

In this article, I will describe what TypeScript is, explain how to learn it and point out how it's different from JavaScript.

What is Typescript ❓

When we hear a word like TypeScript, we might wonder, what is that? πŸ€”

TypeScript is a strongly typed programming language developed by Microsoft that builds on JavaScript, Typescript is a Superset of JavaScript compiled to plain JavaScript.

Is learning Typescript worth it?

Why I use Typescript in my project 🧐

1. Better code reliability

Types help catch errors early before running your code. This results in more reliable code that is less prone to runtime bugs. For example:

  function multiply(a: number, b: number) {
    return a * b;
  }

  multiply(2, "3"); // Type error, string not assignable to number

Here you can see in the example that TypeScript will catch the type error at compile time instead of runtime.

2. Easier code refactoring

Typescript has static types; the compiler can catch errors caused by refactoring. This makes it much easier and safer to rename variables and functions.

3. Better code readability

Types make your code self-documenting. They clearly show the intended usage of variables and functions, making the code easier to read and understand.

4. Better IDE support

The TypeScript compiler provides rich information to IDEs like VS Code. This enables features like:

  • Auto-complete suggestions

  • Error highlighting

  • Go to definition

  • Find references

This makes development more productive.

5. Supports future JavaScript features

TypeScript implements upcoming ECMAScript standards before browsers do. This lets you use new JS features while targeting older browsers.

How Typescript Different from the JavaScript❓

TypeScript and JavaScript have some key differences πŸ‘‡

Typescript has a Static Type system while JavaScript has a Dynamically Type System Let me explain with one example

  • In TypeScript, you can define the types of variables and functions:

      let name: string = "John";
    
      function add(x: number, y: number): number {
        return x + y; 
      }
    
  • In JavaScript, variables can hold any type of data:

      let name = "John";
    
      function add(x, y) {
        return x + y;
      }
    

The type system in TypeScript helps catch errors early and provides better editor support.

Compilation

TypeScript code needs to be compiled to JavaScript to run in browsers:


  console.log("Hello from TypeScript!");

You compile it to JavaScript using the TypeScript compiler:

  tsc hello.ts

This generates hello.js which you can run in the browser.

JavaScript code, on the other hand, can run directly in browsers.

Now One Question has come to your mind Should I be able to learn TypeScript without JavaScript

Answer is No

In short, while it is technically possible to learn TypeScript without any prior JavaScript knowledge, it is generally not recommended. Here are the reasons why:(

  • TypeScript is a superset of JavaScript, meaning it builds on top of JavaScript and adds more features like static typing. Without understanding the basics of JavaScript, it will be difficult to grasp many TypeScript concepts.

  • TypeScript compiles to JavaScript, so without understanding JavaScript, you won't fully understand how TypeScript works and what the compiled output looks like.

  • Most TypeScript tutorials and learning resources assume a basic knowledge of JavaScript. They explain TypeScript in the context of JavaScript and compare the two languages.

  • My recommendation would be to first learn the basics of JavaScript - variables, functions, objects, etc. This will provide a solid foundation for learning TypeScript. Then, move on to TypeScript and see how it builds upon JavaScript with features like type annotations, interfaces, and classes.

  • Once you have a good grasp of both languages, switching between them will be fairly seamless. But starting with JavaScript first will set you up for success when learning TypeScript.

What are the Drawbacks of TypeScript 😞

  • TypeScript takes longer code to write than JavaScript code, as you have to specify types, so for smaller solo projects it might not be worth using it.

  • TypeScript has to be compiled – which can take time, especially in larger projects.

But the extra time that you have to spend writing more precise and Readable code and compiling will be more than saved by how many fewer bugs you'll have in your code.

For many projects – especially medium to large projects – TypeScript will save you lots of time and headaches


How to Setup Typescript ⚑

Install Node and the TypeScript Compiler

First, ensure you have Node installed globally on your machine.

Then install the TypeScript compiler globally on your machine by running the following command:

npm i -g typescript

To check if the installation is successful (it will return the version number if successful Install for my case it's 5.2.2 in your case may be different

tsc -V

TSC will compile the code into JavaScript and output it in a file called index.js:

var sport = 'football';
var id = 5;

If you want to specify the name of the output file:

tsc index.ts --outfile file-name.js

If you want TSC to compile your code automatically, whenever you make a change, add the "watch" flag:

tsc index.ts -w

An interesting thing about TypeScript is that it reports errors in your text editor whilst you are coding, but it will always compile your code – whether there are errors or not.

For example, the following causes TypeScript to immediately report an error:

var sport = 'football';
var id = 5;

id = '5'; // Error: Type 'string' is not assignable to 
type 'number'.

But if we try to compile this code with tsc index, the code will still compile, despite the error.

This is an important property of TypeScript: it assumes that the developer knows more. Even though there's a TypeScript error, it doesn't get in your way of compiling the code. It tells you there's an error, but it's up to you whether you do anything about it.

How to Set Up the ts config File

The ts config file should be in the root directory of your project. In this file we can specify the root files, compiler options, and how strict we want TypeScript to be in checking our project.

First, create the ts config file:

tsc --init

You should now have a tsconfig.json file in the project root.

Here are some options that are good to be aware of (if using a frontend framework with TypeScript, most if this stuff is taken care of for you):

{
    "compilerOptions": {
        ...
        /* Modules */
        "target": "es2016", // Change to "ES2015" to compile to ES6
        "rootDir": "./src", // Where to compile from
        "outDir": "./public", // Where to compile to (usually the folder to be deployed to the web server)

        /* JavaScript Support */
        "allowJs": true, // Allow JavaScript files to be compiled
        "checkJs": true, // Type check JavaScript files and report errors

        /* Emit */
        "sourceMap": true, // Create source map files for emitted JavaScript files (good for debugging)
         "removeComments": true, // Don't emit comments
    },
    "include": ["src"] // Ensure only files in src are compiled
}

To compile everything and watch for changes:

tsc -w

Note: when input files are specified on the command line (for example, tsc index), tsconfig.json files are ignored.

Otherwise, you can use Typescript Official Playground Click here to Redirect to Playground


Thanks for reading! πŸŽ‰

I hope that was useful for you For more from me, you can find me on Twitter

happy hacking πŸ’œ

Β