Learn Typescript Basics in 10 Minutes

Learn Typescript Basics in 10 Minutes

ยท

5 min read

What is Typescript?

Typescript is a superset of Javascript, it can do everything that Javascript can do, plus more! It is open-source, created by Microsoft, and it is becoming more and more popular every year. In Typescript, you explicitly assign types to variables, parameters, return values, etc then you would compile it to Javascript. It is important to remember:

Javascript is dynamic meaning variables aren't interpreted until when we run our code.

Typescript is static meaning variables are interpreted as we declare them, before running code.

superset.jpg

Why should I learn it?

Catch errors now, save time later

The main reason to learn Typescript is to catch bugs earlier in IDE, rather than having hard-to-fix errors in the long run. Since it's a superset of Javascript, the learning curve isn't very steep, you can grasp the concepts pretty quickly. It feels like normal Javascript with superpowers because now you can declare the type on variables, giving you robust code.

Setting up workflow

Open up your code editor (for me VScode) complete the following steps:

  1. Install typescript globally:
    npm install -g typescript
    
  2. Ensure you have properly installed typescript by checking the version:
    tsc -v
    
  3. Create your index.ts file, this is what you will write Typescript in:
    touch index.ts
    
  4. Set up tsconfig.json which enables you to change the compilerOptions for your project. You will notice there are a lot of options, this may seem overwhelming. However, there are only a few things we need to change in the configuration file.

    tsc --init
    
  5. Go into your config file and change the following:

"compilerOptions": {
/* Language and Environment */
"target": "es6",
"watch": true,

/* Modules */
"rootDir": "./src"

/* Emit */
"outDir": "./dist",
}
  • target: es6 - Sets our compiled Javascript to the modern version, ES6
  • watch: true - Automatically compiles our code to Javascript when we save TS file.
  • rootDir: './src' - Sets the root directory to './src' which holds the input Typescript files.
  • outDir: './dist' - Sets the out directory to './dist' which holds the compiled Javascript files.
  1. Next, create the folders that we mentioned in Step 5 that hold our input and output files. Inside of the terminal input:
mkdir dist src

This creates the two folders we need. Now, move the index.ts file into the src directory.

  1. Lastly, you need to go into watch mode so that your Typescript code gets automatically compiled into Javascript code. In your terminal enter:
    tsc
    

Great job, we now have the basic setup for Typescript, let's write some code!

Basic Syntax

Let's start with declaring variables, declare it how you would in Javascript to start. After your variable name, add a colon : along with the type the variable it is. This will make your variable only allowed to that specific type.

Basic / primitive types:

// number 
let age: number = 21
// string 
let personName: string = 'Kyle'
// boolean
let isSingle: boolean = false
// any 
let person: any = 'any type'
// array
let testScores: number[] = [94, 87, 76, 90, 99]

Notes:

  • type any is the default, this means you can set the variable to any type
  • type array is written with either string number or any type followed with brackets []

Screen Shot 2022-02-13 at 1.54.56 PM.png

Notice in the picture when I set the type of age to number, if I tried to reassign it to a string, an error would pop up saying: String is not assignable to type number

Tuple

For arrays, if you have types that are different and need to be in a certain order, use a tuple:

// tuple 
let friend: [number, string, boolean] = [18, 'Hailey', true]

This makes it so you can only have your array in this format, in the order of number, string, and boolean.

We can also create an array of tuple arrays or 2d array. This is if you have multiple arrays that all need to be a certain type:

// tuple array 
let friendsFamily: [number, string][]
friendsFamily = [
    [50, 'Ally'],
    [12, 'John'],
    [6, 'Spots']
]

Union

If you need a type to be either one or another type, use union. It is similar to the or operator in Javascript, to separate the values use the pipe |:

// union 
let id: string | number

id = 7213
// or
id = "t89sa-11"

Enum

Enumerated values are used to define a set of named constants. They are good to prevent random number assignments.

// enum 
enum SocialMedia { Instagram, Facebook, Twitter, Reddit, Snapchat }

const user1: SocialMedia = SocialMedia.Instagram
const user2 = SocialMedia.Reddit

Objects

Objects can be with curly braces {} along with the types when declaring the variables, then set the object values after the }.

// objects 
const dog: {
    age: number, 
    dogName: string
} = {
    age: 12,
    dogName: 'Heidi'
}

Or assign the type to a variable name, then use that name as the type in another line. This is the preferred method because it is easier to read. For this example the name is Dog

type Dog = {
    age: number,
    dogName: string
}

const dog: Dog = {
    age: 12,
    dogName: 'Heidi'
}

Here is a cheat sheet made by Jelvix which shows differences between Javascript and Typescript. It's also recommended that you save this article to reference in the future if you ever forget any of the basics ๐Ÿ˜‰.

cheatsheet.jpeg

Conclusion

Typescript is a growing technology that is well worth learning because it will prevent headache-inducing errors in the future. It is great to have in your toolbox of languages, many developers believe it will grow more and more every year.

Thank you for reading!! Look out for my upcoming articles about more in-depth concepts in typescript. Connect with me at Twitter Github

ย