Typescript Cheatsheet Syntax Part 1

raaynaldo

Raynaldo Sutisna

Posted on April 15, 2021

Typescript Cheatsheet Syntax Part 1

What is Typescript?

According to Maximilian Schwarzmüller, "Typescript is a Javascript superset" Typescript is not completely a new language, but Typescript always compiles to Javascript. My analogy maybe is like body(JS) + armor(TS). Typescript makes Javascript is stronger because Javascript is a loosely typed language, and Typescript is a strongly typed language. I will explain what's the difference between loosely typed language and strongly typed language.

Javascript is a loosely typed language because we have the flexibility to assign without declaring a type of variable.

Try to run this snippet below into our browser console.

function sum(a, b){
  return a + b
}

const firstNumber = '2';
const secondNumber = 5;

const total = sum(firstNumber, secondNumber)
console.log(total)
Enter fullscreen mode Exit fullscreen mode

alt text

Yes, of course. The answer is 25. this is one of the problems of javascript is a loosely typed language.

We can check what's the type of parameters, but we must add more chunks of codes there.

function sum(a, b){
  if(typeof a === 'number' && typeof b === 'number'){
    return a + b;
  } else {
    return +a + +b;
  }
}

const firstNumber = '2';
const secondNumber = 5;

const total = sum(firstNumber, secondNumber)
console.log(total)
Enter fullscreen mode Exit fullscreen mode

That's why Microsoft develops Typescript. Here is the code of how Typescript solves the problem.

function sum(a: number, b: number) {
  return a + b;
}

const firstNumber = 2;
const secondNumber = 5;

const total = sum(firstNumber, secondNumber);
console.log(total);
Enter fullscreen mode Exit fullscreen mode

We just need to specify the type of the parameter.

Installation

Install the node.js because we need to install typescript from npm

You can download it from here.

I would recommend using Node.js Version Manager because it will be great for the future if you want to change the node version easily. I'm using fnm

npm install -g typescript
Enter fullscreen mode Exit fullscreen mode

after you install the typescript globally, you can run this command below to convert .ts to .js

tsc "filename"
Enter fullscreen mode Exit fullscreen mode

Basic Syntax

You can try to clone/fork this project, so you can follow along with my tutorial.

Install the packages

npm install
Enter fullscreen mode Exit fullscreen mode

Compile the Javascript

tsc app.ts
Enter fullscreen mode Exit fullscreen mode

Start the server

npm start
Enter fullscreen mode Exit fullscreen mode

Play around in the app.ts file

Primitive Types (string, number, and boolean)

Every type in Javascript exists in TypeScript. string, number, boolean are the primitive types in Javascript. Let's see the chunk of code below.

try to copy to the app.ts file in the project.

function sum(a: number, b: number, message: string, printResult: boolean) {
  const result = a + b;

  if (printResult) {
    console.log(message + result);
  }
}

const num1 = 25;
const num2 = 10;
const message = 'The total is ';
const printResult = true;

sum(num1, num2, message, printResult);
Enter fullscreen mode Exit fullscreen mode

Compile to Javascript

tsc app.ts
Enter fullscreen mode Exit fullscreen mode

Try to change the variable type of num2 to be a string. It will give you an error message when you compile again.

alt text

PS: Typescript will be compiled the code to Javascript even though you have some errors, but there are warning in the console like the screenshot above.

Object

Declaring the Object type is quite similar with other primitive types.

const dog: object = {
  name: 'roger',
  age: 3,
};
Enter fullscreen mode Exit fullscreen mode

However, we can even specify the attributes of the object.

const dog: {
  name: string;
  age: number;
} = {
  name: 'roger',
  age: 3,
};
Enter fullscreen mode Exit fullscreen mode

So the variable dog can only receive an object with those specific attributes.

Array

We should declare also what's the variable inside the array, and the array can only receive the variable that has been declared.

let programmingLanguages: string[];
programmingLanguages = ['Javascript', 'Typescript', 'Ruby', 'Python'];
Enter fullscreen mode Exit fullscreen mode

If we want to make the array is flexible with any type, we can use any variable. However, it is not good to use it because we remove the idea of strongly typed language.

let programmingLanguages: any[];
programmingLanguages = ['Javascript', 'Typescript', 1, true];
Enter fullscreen mode Exit fullscreen mode

Tuple

Javascript doesn't have tuple, but programming languages such as C# and Java, have it. So, what is Tuple? A tuple is quite similar to an array, but a tuple is a fixed-length array and the type of each value can be different.

let role: [number, string];
role: [1, "Web Developer"]
Enter fullscreen mode Exit fullscreen mode

Enum

When we need to put some contact values, Enum is the answer to our needs.

the value of this enum will start from 0, 1, and 2 because we didn't declare any value.

enum Role { ADMIN, READ_ONLY, AUTHOR }
console.log(Role.READ_ONLY); // 1
Enter fullscreen mode Exit fullscreen mode

If we declare a number in the first enum, the following value of the enum will be increased.

enum Role { ADMIN = 5, READ_ONLY, AUTHOR }
console.log(Role.READ_ONLY); // 6
Enter fullscreen mode Exit fullscreen mode

Enum mustn't declare the number, but we can also declare to string.

enum Role { ADMIN = 'ADMIN', READ_ONLY = 'READ_ONLY', AUTHOR = 'AUTHOR' }
console.log(Role.READ_ONLY); // READ_ONLY
Enter fullscreen mode Exit fullscreen mode

Enum Typescript documentations is here

Any

Any is the special type in Typescript. Any can receive any type in the variable, so it loses the strict of Typescript. I don't recommend using it all the time.

let anyType: any;
anyType = 1;
anyType = "hello";
anyType = [1,2,3];
anyType = {};
anyType = false;
Enter fullscreen mode Exit fullscreen mode

Union Types

union type let the variable receive more than one type by using |

let id: string | number;
id = 10; // Ok
id = "ID001"; // OK
id = [1, 2]; // Error
Enter fullscreen mode Exit fullscreen mode

Type Aliases

We can change the type name as we want, but it will be useful for complicated types such as object and union.

type ID = string | number;
let id: ID
id = 10; // Ok
id = "ID001"; // OK
id = [1, 2]; // Error
Enter fullscreen mode Exit fullscreen mode

Literal Types

This type lets the variable only receive the same value that has been declared.

let alwaysOne: "One";
alwaysOne = "One"; // OK
alwaysOne = "Two"; // Error
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
raaynaldo
Raynaldo Sutisna

Posted on April 15, 2021

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

Sign up to receive the latest update from our blog.

Related