Typescript

iali1995

ibrahim ali

Posted on March 16, 2021

Typescript

For this and all other upcoming blogposts, I wanted to cover topics that were most relevant to tech professionals right now. So I posted a question in my friend's dev-based discord for suggestions on topics and I got few different responses but the one consensus among them of a relevant topic was Typescript.

The first thing to know about typescript is that it IS javascript, or rather it's a superset of javascript, meaning that it is a language built on top of javascript and any javascript is a valid typescript. It was designed by Anders Hejlsberg at Microsoft and is maintained by Microsoft. its first version 0.8 was released in October 2012. In the following years a few more major updates were released leading all the way up to Typescript 4.0 which was released Aug 20th, 2020.

FEATURES

Compiling
Typescript doesn't actually run anywhere. To execute typescript it needs to be compiled. The tsc command runs the typescript compiler. After installing typescript globally with the npm i -g command, you can create a .ts file which is where you can write your typescript code. Then you can write whatever typescript code you want in the file and when you want to compile you can run the tsc command on your index.ts file and the transpiler will compile it into javascript for you in a .js file of the same name. You can also create a config file and set up a few options there to automate some of the things the transpiler can do for you.

Typing

Typescript's biggest feature is that it is object-oriented and strongly-typed. Javascript is a loosely-typed, an interpreted language, which while providing much flexibility, can allow many bugs to go unnoticed until they wreak havoc at production time.

const sum = (num1, num2) => {
  return num1 + num2
}; /*javascript will allow any datatype to be passed as a parameter here*/

sum(3, 4); // returns 7
sum('A', 4); // will return 'A4'
Enter fullscreen mode Exit fullscreen mode

With Typescript on the other hand you can declare the type a variable needs to be to narrow-down possible bugs that may arise from passing the wrong data-type into the arguments of a function.

There are two types of typing in typescript. Implicit typing and explicit typing. Implicit typing happens when you declare a variable and assign a datatype to it such as a string. Typescript will automatically note it as that specific data type so if it reassigned to another data type such as a number it will throw an error right there.

let greeting = 'Hello world'

greeting = 27; //it will prevent you from reassigning greeting to //a number
Enter fullscreen mode Exit fullscreen mode

You can also explicitly type variables and parameters with the colon. Right after the declaration of the variable, you can type the colon and then its data type as defined by javascript.

const sum = (num1: number, num2: number) {
  return num1 + num2
};

sum(3, 4); //returns 7
sum('A', 4); //is highlighted an disallowed because num1 can only //be a number
Enter fullscreen mode Exit fullscreen mode

To preserve javascript's flexibility if you choose to opt-out of the typing, you can use the tag, or you can declare the variable by itself.

let example;

let example2 : any = 14;

example = 'example';
example = true;   //these should all work.
example2 = 'example2';
Enter fullscreen mode Exit fullscreen mode

Additionally, you can also create your own types.

type Fourteen = 'fourteen' | 14;

let fourPlus10: Fourteen = 14;
let digitFourPlus10: Fourteen = 'fourteen';
Enter fullscreen mode Exit fullscreen mode

Obviously, that is a very basic and redundant example of custom typing. With interface you can type an object, almost like a constructor. You can define an object and what its keys and value datatypes should be

interface Car {
    color: string;
    year: number;
    automatic: boolean;
}

const camry: Car = {
    color: 'silver', //this will work
    year: 2021,      //if i try to add another prop it won't
    automatic: true;
}
Enter fullscreen mode Exit fullscreen mode

Though you can circumvent this, just like the "any" type.

interface Animal {
    name: string;
    species: string;
    age: number;
    [key: string]: any
}

const pet: Animal = {
    name: 'jecko',
    species: 'cat',
    age: 2,
    idiot: true
}
Enter fullscreen mode Exit fullscreen mode

With functions, you can type both the arguments that they take and the result that they return. Just like the variables you can type the parameters and then after the parameters and before the bracket you can type what the function should return.


function greet (timeOfDay: string, name: string) : string {
    return `good ${timeOfDay} ${name}!`
}`
Enter fullscreen mode Exit fullscreen mode

If you don't want to type the function replace whichever type with void.

 function laugh () : void {
  console.log('hahahahaha')
}
Enter fullscreen mode Exit fullscreen mode

You can type arrays as well. This can be useful in a few different scenarios, such as if you want an array of just numbers or especially when dealing with an array of objects.

const numArray: number[] = [];

numArray.push(1); //works
numArray.push(2); //works
numArray.push('hello'); //throws error
Enter fullscreen mode Exit fullscreen mode

You can also create touples, which are arrays with a fixed amount of indexes. Here you can declare an array that takes a specific amount of arguments each with its own specific type. But if you strongly type an array like this, when it's being declared it will demand that all the indices be present with their appropriate values. This can be circumvented with the "?" optional.

type sixSidedDie = [number, number, number, number, number, number];

const dice: sixSidedDie = [1,2,3,4,5,'six']; //won't work
const dice: sixSidedDie = [1,2,3,4,5];//won't work

type sixSidedDie = [number, number, number, number, number, number?];

const dice: sixSidedDie = [1,2,3,4,5]//will work
Enter fullscreen mode Exit fullscreen mode

Third-party libraries
Typescript supports almost all javascript libraries. Typescript also supports nearly all javascript libraries.

💖 💪 🙅 🚩
iali1995
ibrahim ali

Posted on March 16, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related