A simple introduction to TypeScript

By Prajwal Haniya

Tech-letter #6 | January 14,2023

A Simple introduction to TypeScript

I learned JavaScript at a very early stage during my college. It took me a few months of experience in hardcore coding using JavaScript for me to know why types are essential. So here I am understanding TypeScript.

Whenever you write JavaScript code, the browser/editor (unless you have installed ESLint or any such tool) won’t give you feedback if your code isn’t right. To know your mistake you need to write the code and then execute it, only then you will be notified of the mistake in your code. Sometimes it feels frustrating because you could have avoided errors if you had notified while writing the code. So here comes TypeScript to help us write better code with fewer bugs.

In short,

TypeScript provides code analysis for JavaScript

In JavaScript code, you can usually mix the type of a value by assigning the same variable with a string and later a number. TypeScript uses a concept called type inference and prevents the mixing of types for the same variable.

Definition of a type from the book TypeScript in 50 lessons:

A type is a classification of data that defines the operations that can be done on that data, the meaning of the data, and the set of allowed values.

TypeScript cares a lot about the shape or structure of objects and functions.

Understanding the tsconfig.json file might be slightly confusing. But, you can browse online for the problems there are many resources that can help you.

Let us write a simple TypeScript code

function addNumbers(x: number, y:number) {
    return x + y;
}

console.log(addNumbers(1, 2));

The above code is for adding two numbers. The main problem when you write a simple JS function is that it doesn’t check that you pass a number or a string. In a JS function, you can pass a string and a number and it returns the value by concatenating them. But, in typescript, it throws an error while writing the code itself, as a function will be expecting numbers only.

Articles that I read this week

  1. Best practices for REST API security: Authentication & authorization
  2. An introduction to OAuth2
  3. Complete guide to protecting your APIs
  4. The TypeScript Handbook
  5. Migrating from JavaScript to TypeScript