DEV Community

Cover image for TypeScript: A beginner's guide with emojis 🤗
Fredy Sandoval
Fredy Sandoval

Posted on

TypeScript: A beginner's guide with emojis 🤗

Is basically telling what type something is.

For example let say we have a box,
and we want to tell people to only put eggs in the box.



let myBox; // 📦


Enter fullscreen mode Exit fullscreen mode

In real life we would put a sticker in the box saying "only eggs
please 📄", in TypeScript we do the same, we add a "type" saying what something is and only accepts.



  Variable           Type            value
┌────┴─────┐     ┌────┴─────┐      ┌───┴───┐
let myBox_📦  :  onlyEggs_📄   =   "🥚🥚🥚";
                               
               Separator        Assignment operator


Enter fullscreen mode Exit fullscreen mode

There are 3 basic types in TypeScript



let isDone: boolean = false;              // 😀 or 😟

let lines: number   = 42;                 // 0️⃣1️⃣2️⃣3️⃣4️⃣5️⃣...

let name: string    = "John";             // 📃


Enter fullscreen mode Exit fullscreen mode

When it's impossible to know, there is the "Any" type



let notSure: any = 4;                     // 🤷‍♂️ Not sure

notSure = "I'm a string";                 // I can change it later

notSure = false;                         // maybe a boolean


Enter fullscreen mode Exit fullscreen mode

There are typed arrays



let list: number[] = [1, 2, 3];

// or with emojis:
        Only chickens please!
              ┌─┴─┐ 
let chickens: 🐔[] = [🐣,🐤,🐥,🐓];


Enter fullscreen mode Exit fullscreen mode

Alternatively you can use Array which It's same as Type[]



let list: Array<number> = [1, 2, 3];

// or with emojis
let listOfChickens: Array<🐔> = [🐣,🐤,🐥,🐓];


Enter fullscreen mode Exit fullscreen mode

Enumerations also known as enums:



enum Square { Red, Green, Blue };         // 🟥, 🟩, 🟦

// This can be understood better by seeing what Enumerations 
// are compiled to in JavaScript:
Square = { 
           0       :   'Red', 
           1       :   'Green', 
           2       :   'Blue', 
           Red     :    0, 
           Green   :    1, 
           Blue    :    2,
          };

// Now that you know is just an object, 
// you can access it by name or number.
console.log( Square.Green );              //  🟩
console.log( Square[2] );                 //  🟥 

// or in a more complex way
let c: Square = Square.Blue;
console.log( Square[c] );                 //  🟦


Enter fullscreen mode Exit fullscreen mode

Please Comment if you want to see more content like this!
👇 Follow me on Twitter

Twitter

Top comments (0)