DEV Community

Cover image for From JavaScript to TypeScript Crash Course/CheatSheet : Basics
Rahul Banerjee
Rahul Banerjee

Posted on • Originally published at realpythonproject.com

From JavaScript to TypeScript Crash Course/CheatSheet : Basics

TypeScript Compiler

Install

sudo npm install typescript -g
Enter fullscreen mode Exit fullscreen mode

or

brew install typescript
Enter fullscreen mode Exit fullscreen mode

Run the Compiler

tsc <fileName.ts>
Enter fullscreen mode Exit fullscreen mode

If I have a file named "index.ts"

tsc index.ts
Enter fullscreen mode Exit fullscreen mode

The TypeScript compiler essentially converts a TypeScript File to a JavaScript File. It produces a new .js file.

index.ts -> index.js (a new file, doesn't overwrite .ts file)
Enter fullscreen mode Exit fullscreen mode

It also checks for errors in your code

tsconfig.json File

It helps you configure your compiler.
To create a sample tsconfig.json fil

tsc -init
Enter fullscreen mode Exit fullscreen mode

You can configure the root to all your typescript files and the destination where you'd like the converted javascript files to be stored

// tsconfig.json 
{
   "src" : "path to root folder with typescript files",
   "dist": "path to the folder where you want converted javascript files to be stored"
}
Enter fullscreen mode Exit fullscreen mode

If you get errors while importing JS Modules, add the following to tsconfig.json

  "compilerOptions": {
    ...
    "allowJs": true,
    "checkJs": false,
    ...
  }
Enter fullscreen mode Exit fullscreen mode

Declaring Variable Types

var variableName : type = value
Enter fullscreen mode Exit fullscreen mode

Example

var myNumber : number = 1
var myString : string = "Hello World"
Enter fullscreen mode Exit fullscreen mode

Basic Supported types

  • number (Includes integers, float, and double)
  • string
  • boolean
  • undefined
  • null
var myString : string = 'Hello World';

myString = 1337; 
// Error: Type 'number' is not assignable to type 'string'
Enter fullscreen mode Exit fullscreen mode

Unlike JavaScript, it performs type checking and returns an error if we try to assign a value that has a different datatype than the one initially assigned.


The "Any" Tyoe

Any is like a wild card type. When you set a variable's type to any, it is more or less JavaScript since no type check is performed

var randomVariable : any = 10
randomVariable = false // TypeScript doesn't give an error
Enter fullscreen mode Exit fullscreen mode

Function Parameter Types

function myFunction (param1 : number, param2: boolean)
{

}
Enter fullscreen mode Exit fullscreen mode

It follows a similar syntax to declaring types for variables. If you declare the types of the parameters, type checking will be performed when you invoke the function

myFunction(1,false) // Works Fine

myFunction("1",true)
// ERROR: Argument of type 'string' is not 
// assignable to parameter of type 'number'.
Enter fullscreen mode Exit fullscreen mode

Arrow functions

const myFunction  = (param1 : number, param2: boolean) => {}
Enter fullscreen mode Exit fullscreen mode

Optional Parameters

function funcOptional(param1: number, optionalParam ?: string){

}

funcOptional(20) // Works Fine
funcOptional(20,"Hello") //Works Fine
Enter fullscreen mode Exit fullscreen mode

Put a question mark before the colon to denote an optional parameter

Arrow Functions

const funcOptional = (param1: number, optionalParam ?: string) => {}
Enter fullscreen mode Exit fullscreen mode

RULE: Non-Optional/Required Parameters CAN NOT follow Optional Parameters

function funcOptional(param1: number, 
optionalParam ?: string, requiredParam : string) 
{

}

//ERROR: A required parameter cannot follow an optional parameter.
Enter fullscreen mode Exit fullscreen mode

Default Parameters

function funcDefault(param1: number, defaultParam: number = 10) 
{

}

funcDefault(10)
funcDefault(10,20)
Enter fullscreen mode Exit fullscreen mode

A default parameter makes the parameter optional, you don't need a question mark if you are setting a default value for the parameter.

Arrow Function

const funcDefault = (param1: number, defaultParam: number = 10) => {}
Enter fullscreen mode Exit fullscreen mode

Function Return Type

function myFunction() : number{
  return 1
}
Enter fullscreen mode Exit fullscreen mode

Void Return Type

Use this when your function doesn't return anything

function voidFunction(): void{
  console.log("Hello World")
}
Enter fullscreen mode Exit fullscreen mode

Arrow Functions

 const myFunction = () : number => {
  return 1
}

const voidFunction = (): void => {
  console.log("Hello World")
}
Enter fullscreen mode Exit fullscreen mode

Functions Comments

/**
* Statement 1
* Statement 2 
*/
Enter fullscreen mode Exit fullscreen mode

It supports the syntax for JavaScript Comments as well


Type Inference

In some cases, the type doesn't have to be explicitly specified. TypeScript can infer the type

function myFunc(num1: number, num2: number){
  return num1 + num2
}
Enter fullscreen mode Exit fullscreen mode

We do not need to specify the return type of the function above, TypeScript can infer that the return type is a number since the addition of two numbers will always return a number.

var someNum = myFunc(10,20)
Enter fullscreen mode Exit fullscreen mode

In the above case as well, we do not need to specify the type of the variable. The type of the variable can be inferred by TypeScript based on the return type of the function. The myFunc functions return a number type therefore the type of the variable someNum is also a number.


Declaring an Array Type Variable

We need to put a ' []' after the datatype

let numArr : number[] = [1,2,3,4,9.81]
// Array of numbers, if you try to insert any non-number value, 
// it will give an error

let strArr : string[] = ["Hello" , "World" , "TypeScript"]
// Array of string values


let mixedArr : any[] = [1 , 2 ,'Hello' , 'World', false]
// Array of mixed data types
Enter fullscreen mode Exit fullscreen mode

Multi-Dimensional Array

Simply add another ' [] ' to the data type.

let multiArr : number[][] = [
  [1,2],
  [2,3],
  [3,4]
]

// number[] [] can also be writtedn as 
// (number[])[]


let threeDimArr : number[][][] = [
  [
    [1,2] , [2,3]
  ],
  [
    [1] , [2]
  ]
]

// Similary number[][][] can be written as 
// ((number[])[])[]
Enter fullscreen mode Exit fullscreen mode

Interfaces

Interfaces let you combine multiple data types or variables. Below are a couple of examples

interface Coordinate{
  x : number,
  y: number
}


interface Student{
  fname: string ,
  lname: string,
  age?: number,
  ID?: string
}
Enter fullscreen mode Exit fullscreen mode

We can also set some variables as optional. Eg: in Student, the age and ID are optional.

We can not initialize the variables.

Below is how we could use the above interfaces

const func = (
  student: Student,
  coordinate: Coordinate
) => {
  console.log(`${student.fname} stays at (${coordinate.x},${coordinate.y})`)
}


func(
  {fname: "Rahul", lname: "Banerjee", age: 21},
  {x: 10, y :20}
)

Enter fullscreen mode Exit fullscreen mode

Import and Export in TypeScript

Export

We can use the export keyword

//index.ts

export interface Coordinate{
  x : number ,
  y: number
}

const func = ( 
  p1: Coordinate,
  p2: Coordinate
): Coordinate => {
    return {
      x: p1.x + p2.x,
      y: p1.y + p2.y
    }
}

export {func as func_add_points}
Enter fullscreen mode Exit fullscreen mode

Import

import {Coordinate} from './index'
import index = require("./index")
import * as fs from 'fs'


const p1: Coordinate = {
  x: 1,
  y: 2
}

const p2: Coordinate = {
  x: 5,
  y: 6
}

console.log(
index.func_add_points(p1,p2)
)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)