DEV Community

Aditya Sharan
Aditya Sharan

Posted on

TypeScript Quick Guide 101

One appropriate next step for the React application would be to integrate TypeScript in order to add a layer of robustness and security.

TypeScript is a JavaScript superset that adds new features to the language, being one of the most important ones that, with TypeScript, you can add type-checking to your projects. TypeScript is the step that JavaScript needed to look like a high-level programming language (like Java).

My intention with this (short) article, is to write a quick guide with some of the most important features TypeScript has, without diving that much. So, let’s begin.

Most Important Types
: string
: number
: boolean
: array
: any
: void
: null
: undefined
How to apply types to your variables

let myVariable: number;
Enter fullscreen mode Exit fullscreen mode

An array filled only with elements of a specific type type

let strArr: string[];


let strArr: Array<string>;
Enter fullscreen mode Exit fullscreen mode

You use tuples when your array needs to contain a specific type of values in certain indexes. If the array overpass the size of the tuple, an error would not be throw. The only condition is to fulfill the requirements of the tuple.

let strNumTuple: [string, number];

strNumTuple = [3, ‘Hello’, 1, 2, 3]: // this would be correct.
Enter fullscreen mode Exit fullscreen mode

Adding types to functions
You can add types to the parameters of a function, so, when the function is called, the types of the arguments would need to match. The type after the parameter represents the type of value the function should return.

const mySum = function(num1:number,num2:number):number{

return num1 + num2;

Enter fullscreen mode Exit fullscreen mode

Let’s say you need that the argument passed to your function needs to be an object with values of specific types. This is one case when interfaces come in handy.

interface Todo{

title: string;

text: string;

/* the object passed as an argument 
should contain at least values with those types.*/

function showTodo(todo: Todo){

console.log(todo.title+’ ‘+todo.text)


let myTodo = {title:’Trash’, text:’take out trash’};
Enter fullscreen mode Exit fullscreen mode

And this is all for now…
Being TypeScript one of the best ways to strengthen applications that need JavaScript, it gains every day more and more importance in nowadays market. So, these days, to only learn JavaScript without Type it’s kind of pointless, and even if JavaScript evolves tomorrow and add features similar to TypeScript, these features are (almost for sure) going to be implemented in a very similar way (well, those are just my predictions).

Top comments (0)