Learning TypeScript — Installation & Basic Types

Photo by David Klein on Unsplash

TypeScript as a Compiler

TypeScript compiles to JavaScript, more specifically ES3 according to the docs.

Installation

npm install typescript --save-dev
npx tsc
{
"compilerOptions": {
"module": "CommonJS", // Default is CommonJS for ES3 or ES5, and ES6 for ES6 or higher
"target": "ES2017",
"outDir": "lib", // output directory
}, "include": ["src"] // inputs: specify list of files or folders}

Basic Types

TypeScript being a superset for JavaScript would have more types supported.

Boolean

let isTrue: boolean = true;

Number

let decimal: number = 10;
let binary = 0b101; // 5
let hex: number = 0x9D2; // 2514
let big: bigint = 100n;

String

let name: string = 'Bryan';
let language: string = "JavaScript";
let sentence: string = `Hi, my name is ${name} and I think ${language} is great!`

Array

let list1: number[] = [1, 2, 3];
let list2: Array<number> = [1, 2, 3]; // Generic array type

Tuple

let tuple: [string, number] = ['hi', 123];
tuple = [123, 'hi'] // Error

Enum

enum Languages = {
javascript, // default value assigned is 0
typescript, // 1
coffeescript, // 2
}
let favLanguage: Languages = Languages.typescript; // 1
enum Languages = {
javascript = 10,
typescript = 15,
coffeescript,
}
let notFavLanguage: Languages = Languages.coffescript; // 16 without any value assignment

Unknown

let notSure: unknown;
notSure = 123; // Could be a number
notSure = true; // Could be a boolean even
let notSure: unknown;
notSure = 2;
if(typeof notSure === 'string') {
const isString: string = notSure; // After checking if it is a string, we know for sure it is of type "string". Same for below.
}
if(typeof notSure === 'number') {
const isNumber: number= notSure; // Value is 2
}

Any

let anything: any = 4;
anything.pop() // Ok
anything.toFixed() // Ok. Works but TS does not check if it does
anything.a.b.c.d.whatever // Ok. Works too as TS does not check.

Void

let itIsVoid: void = undefined; //Ok
itIsVoid = null; // Ok. only in non-strict null check mode

Nulls and Undefined

let a: null = null; // Ok
a = 123; //Error
let b: undefined = undefined //Ok
b = 123; // Error

Never

function error(message: string): never {
throw new Error(message);
}
function error2(message: string): never { // inferred type is never
throw new Error(message);
}
function infiniteLoop(): never { // does not reach completion
while(true) { }
}

Object

let a: object = {}; // Oka = []; // Ok
a = null; // Error
a = '123'; // Error
a = 123; // Error

Type Assertions

let notSure: unknown;
let isNum: number = (notSure as number) + 1; // Ok
let notSure2: unknown;
let isNum2: number = notSure2 + 1; // Error as it is unknown

Conclusion

I have a passion for coding.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store