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;
An array filled only with elements of a specific type type
let strArr: string[];
//or
let strArr: Array<string>;
Tuples
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.
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;
}
Interfaces
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’};
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)