Getting Started with Typescript: Part 1

Photo by Clay Banks on Unsplash

Getting Started with Typescript: Part 1

ยท

2 min read

TypeScript Basics: Type Inference and Compilation

Introduction

TypeScript is a statically typed superset of JavaScript that helps catch errors at compile-time, making your code more robust and maintainable. In this blog post, we'll explore two key aspects of TypeScript: type inference and compilation.

Type Inference

One of the key features of TypeScript is its ability to infer types based on the assigned values. Let's take a look at an example:

let id = 5; // TypeScript infers the type 'number' for the variable 'id' 

console.log("ID:", id);

In the code above, we declare a variable 'id' and initialize it with the value 5. TypeScript automatically infers that 'id' is of type 'number' because of the assigned value.

Compilation

To use TypeScript, you need to compile your TypeScript code into JavaScript.

This compilation process is essential for browsers and Node.js to understand your code. Here's how you can compile a TypeScript file:

1. Write your TypeScript code in a .ts file, e.g., script.ts.

2. Open your terminal and run the TypeScript compiler (tsc) on your file:

tsc script.ts

After running the above command, you'll see that a JavaScript file with the same name (script.js) is generated in the same directory. This JavaScript file contains the code compiled from your TypeScript.

Watching for Changes

During development, it's helpful to automatically compile TypeScript whenever you make changes to your code. TypeScript provides a watch mode for this purpose. Here's how to use it:

1. Open your terminal.

2. Run the TypeScript compiler in watch mode:

tsc --watch

With the --watch flag, TypeScript will continuously monitor your .ts files for changes and recompile them whenever you save your code.

Conclusion

TypeScript's type inference simplifies the process of specifying types, reducing the need for explicit type annotations. Additionally, the compilation step ensures that your TypeScript code can be executed by browsers and Node.js. By leveraging these features, you can write safer and more maintainable JavaScript applications.

ย