TypeScript Compiler
Install
sudo npm install typescript -g
or
brew install typescript
Run the Compiler
tsc <fileName.ts>
If I have a file named "index.ts"
tsc index.ts
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)
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
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"
}
If you get errors while importing JS Modules, add the following to tsconfig.json
"compilerOptions": {
...
"allowJs": true,
"checkJs": false,
...
}
Declaring Variable Types
var variableName : type = value
Example
var myNumber : number = 1
var myString : string = "Hello World"
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'
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
Function Parameter Types
function myFunction (param1 : number, param2: boolean)
{
}
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'.
Arrow functions
const myFunction = (param1 : number, param2: boolean) => {}
Optional Parameters
function funcOptional(param1: number, optionalParam ?: string){
}
funcOptional(20) // Works Fine
funcOptional(20,"Hello") //Works Fine
Put a question mark before the colon to denote an optional parameter
Arrow Functions
const funcOptional = (param1: number, optionalParam ?: string) => {}
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.
Default Parameters
function funcDefault(param1: number, defaultParam: number = 10)
{
}
funcDefault(10)
funcDefault(10,20)
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) => {}
Function Return Type
function myFunction() : number{
return 1
}
Void Return Type
Use this when your function doesn't return anything
function voidFunction(): void{
console.log("Hello World")
}
Arrow Functions
const myFunction = () : number => {
return 1
}
const voidFunction = (): void => {
console.log("Hello World")
}
Functions Comments
/**
* Statement 1
* Statement 2
*/
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
}
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)
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
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[])[])[]
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
}
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}
)
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}
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)
)