Concepts for TypeScript
TypeScript is a statically typed superset of JavaScript developed by Microsoft. It adds optional static typing to JavaScript, allowing developers to catch errors early during development and improve code quality and maintainability. TypeScript compiles down to plain JavaScript, making it compatible with existing JavaScript codebases and allowing developers to leverage the latest JavaScript features while providing additional type safety. Its key features include static typing, interfaces, enums, generics, and advanced tooling support, such as code completion and refactoring. TypeScript is widely used for building large-scale web applications, particularly in projects where codebases are expected to grow over time, as it helps reduce bugs, increase productivity, and enhance collaboration among developers.
Print Text
console.log('Hello World!'); console.log("Hello World!");
Comments
// one line comment /* multi line comment */
Variables
function main() { var carCount = 2; let name: String = 'Joe'; const isPurple: Boolean = true; }
Data Types
let carCount:number = 2; let age:number = 15; let seaLevel:number = -10000; let usBudget:number = 11000000000; let lightSpeed:number = 11799312874; let myGPA:number = 3.45; let piValue:number = 3.14159265; let lastLetter:string= 'Z'; let isMale:boolean = true; let myName:string = 'Joe';
Math Op
const carCount = 6; const truckCount = 3; const total: number = carCount + truckCount; console.log(total); const subtract: number = carCount - truckCount; console.log(subtract); const multiple: number = carCount * truckCount; console.log(multiple); const divisible: number = carCount / truckCount; console.log(divisible); // performs division and gets remainder which is 0 const modulo: number = carCount % truckCount; console.log(modulo);
Math Functions
const power: number = Math.pow(3, 6); console.log(power); const root: number = Math.sqrt(16); console.log(root); const floorVal: number = Math.floor(3.14); console.log(floorVal); const ceilVal: number = Math.ceil(4.3); console.log(ceilVal); const roundVal: number = Math.round(3.4); console.log(roundVal); // random number from 0 to 100 const ranNum: number = Math.floor(Math.random() * 100) + 1; console.log(ranNum);
If/Else
const carCount:number = 6; if (carCount > 3) { console.log('More than three cars'); } else if (carCount === 3) { console.log('Equal to three cars'); } else { console.log('Less than three cars'); }
Ternary
const carCount:number = 3; const result:string = (carCount > 2) ? "Yes" : "No"; console.log(result);
Switch
const carCount:number = 3; switch (carCount) { case 1: console.log('One car'); break; case 2: console.log('Two cars'); break; case 3: console.log('Three cars'); break; default: console.log('More than three'); }
Functions
function handleCars( cars:number, wheels:number ):number { const total = cars * wheels; return total; } const result = handleCars(3, 4); console.log(result);
Interpolation
const name:string = 'Joe'; const car:string = 'Mazda'; console.log(`${name} drives a ${car}`)
Type Casting
function squareA(length: number) { const result = Math.pow(length, 2); return result.toString(); } const squareL = "4"; const convertedVal: number = parseInt(squareL); const area:String = squareA(convertedVal); console.log(area);
Date and Time
// get time in milliseconds const milliTime:number = Date.now(); console.log(milliTime); // current year const currentYear:number = new Date().getFullYear(); console.log(currentYear); // create new Date obj const utcDate:number = Date.UTC(2023, 11, 20, 3, 0, 0); const fullDate:Date = new Date(); const date:Intl.DateTimeFormat = new Intl.DateTimeFormat(); // formats date in a more traditional format const formatedDate:string = date.format(fullDate); console.log(formatedDate);
Classes
class Cars { carList: string[]; constructor() { this.carList = []; } addCar(name:string) { this.carList.push(name); } removeFirst() { this.carList.shift(); } getFirstVal():string { if (this.carList.length) { return this.carList[0]; } return ''; } } const newList:Cars = new Cars(); newList.addCar("Honda"); newList.addCar("Mazda"); newList.addCar("Toyota"); newList.removeFirst(); const firstCar:string = newList.getFirstVal(); console.log(firstCar);
Inheritance
class User { private username:string; private password:string; constructor( username:string, password:string ) { this.username = username; this.password = password; } getUsername() { return this.username; } } class Admin extends User { id:string; constructor( username:string, password:string, id:string ) { super(username, password); this.id = id; } getAdminID() { return this.id } } const newAdmin = new Admin( "alpha0", "pw1", "1FE" ) console.log(newAdmin.getUsername()); console.log(newAdmin.getAdminID());
Method Overload
// No Native Support or Implementation
Abstract Class
abstract class Animation { abstract walk(): () => void; abstract run(): () => void; abstract idle(): () => void; } class Human extends Animation { walk() { console.log("Human walks"); } run() { console.log("Human runs"); } idle() { console.log("Human idles"); } } class Zombie extends Animation { walk() { console.log("Zombie walks"); } run() { console.log("Zombie runs"); } idle() { console.log("Zombie idles"); } } const player = new Human(); player.walk(); const zombie = new Zombie(); zombie.run();
Static Class
class Helper { static CircleA(radius:number):number { const power = Math.pow(radius, 2); return 3.14 * power; } static SquareA(length:number):number { return Math.pow(length, 2); } } const circle:number = Helper.CircleA(3); console.log(circle); const square:number = Helper.SquareA(4); console.log(square);
Arrays/Lists
const names:string[] = ['Joe', 'Sam', 'David']; names[1] = "Tom"; const name:string = names[1]; const numItems:number = names.length; console.log(name); console.log(numItems);
Array Methods
const cars:string[] = ['Honda', 'Mazda', 'Toyota']; // creates new array to newlist from index 1 const newList:string[] = cars.slice(1); console.log(newList); // cuts original list at index 1 to returnVal const returnVal:string[] = cars.splice(1); console.log(returnVal); console.log(cars); // add Ford to end of array cars.push('Ford'); console.log(cars); // removes last element Ford from array cars.pop(); console.log(cars); // adds Kia to beginning of array cars.unshift('Kia'); console.log(cars); // removes first element of array Kia cars.shift(); console.log(cars); // sorts array in alphabetical order cars.sort(); console.log(cars);
Concatenation
const carsListKr:string[] = ["Kia", "Hyundai", "Daewoo"]; const carsListJp:string[] = ["Honda", "Mazda", "Toyota"]; const combined:string[] = [...carsListKr, ...carsListJp]; console.log(combined[1]); console.log(combined[4]);
Sort Method
const ages:number[] = [5, 3, 1, 6, 7, 4, 19]; ages.sort(); console.log(ages);
Objects
interface User { first:string, last:string, age:number, retired:boolean, carBrands: string[], fullName: () => string, } const user:User = { first: 'Joe', last: 'Doe', age: 23, retired: false, carBrands: ['Mazda', 'Toyota'], fullName: function () { return `${this.first} ${this.last}` } } console.log(user.first); console.log(user.carBrands[1]); console.log(user.fullName());
Maps (Key/Value)
const carMap:Map<string, string> = new Map(); carMap.set("Joe", "Toyota"); carMap.set("Bob", "Mazda"); carMap.set("Tom", "Ford"); console.log(carMap.get("Tom")); carMap.delete('Tom'); console.log(carMap.keys());
Sets
const cars:Set<string> = new Set(); cars.add("Mazda"); cars.add("Toyota"); cars.add("Honda"); console.log(cars.has("Honda")); cars.delete("Honda"); console.log(cars.has("Honda"));
Stack
const cars:string[] = []; cars.push('Mazda'); cars.push('Toyota'); cars.push('Honda'); console.log(cars[cars.length - 1]); cars.pop(); console.log(cars[cars.length - 1]);
Queues
const cars:string[] = []; cars.push('Mazda'); cars.push('Toyota'); cars.push('Honda'); console.log(cars[0); cars.shift(); console.log(cars[0]);
Linked List
class NodeTest { value: string; next: NodeTest | null; constructor(value:string) { this.value = value; this.next = null; } } class LinkedList { head: NodeTest | null; constructor() { this.head = null; } add(value: string) { const newNode = new NodeTest(value); if (this.head === null) { this.head = newNode; } else { let current = this.head; while (current.next) { current = current.next; } current.next = newNode; } } returnHead():string { return this.head? this.head.value: ""; } traverse() { let current = this.head; while(current) { console.log(current.value); current = current.next; } } } const carList = new LinkedList(); carList.add("Mazda"); carList.add("Toyota"); carList.add("Honda"); console.log(carList.returnHead()); carList.traverse();
Graphs
class Graph { graphMap: {[key: string]: string[]} constructor() { this.graphMap = {}; } addNode(val:string) { this.graphMap[val] = []; } addVertices(node1:string, node2:string) { if(!this.graphMap[node1]) { this.graphMap[node1] = []; } if(!this.graphMap[node2]) { this.graphMap[node2] = []; } this.graphMap[node1].push(node2); this.graphMap[node2].push(node1); } breadthTraverse(start:string) { const queue = [start]; const visited:{[key: string]:boolean} = {}; visited[start] = true; while(queue.length) { const val = queue.shift(); console.log(val); const tempArr = this.graphMap[val as string]; for (let i = 0; i < tempArr.length; i++) { if (!visited[tempArr[i]]) { queue.push(tempArr[i]); visited[tempArr[i]] = true; } } } } depthTraverse(start:string) { const stack = [start]; const visited:{[key:string]:boolean} = {}; visited[start] = true; while(stack.length) { const val = stack.pop(); console.log(val); const tempArr = this.graphMap[val as string]; for (let i = 0; i < tempArr.length; i++) { if (!visited[tempArr[i]]) { stack.push(tempArr[i]); visited[tempArr[i]] = true; } } } } } const newGraph = new Graph(); newGraph.addNode("a"); newGraph.addVertices("a", "b"); newGraph.addVertices("a", "c"); newGraph.addVertices("b", "d"); newGraph.addVertices("b", "e"); newGraph.addVertices("d", "f"); newGraph.addVertices("d", "g"); newGraph.addVertices("d", "h"); newGraph.addVertices("e", "i"); newGraph.addVertices("e", "j"); newGraph.breadthTraverse("a"); newGraph.depthTraverse("a");
For Loops
let names:string[] = ['Joe', 'Alex', 'Bob']; for (let i = 0; i < names.length; i++) { console.log(names[i]); }
While Loops
const carList:string[] = ['Mazda', 'Toyota', 'Honda']; while (carList.length) { console.log(carList[0]); carList.shift(); } console.log(carList.length);
Loop Breaks
const cars:string[] = ['Toyota', 'Honda', 'Mazda']; for (let i = 0; i < cars.length; i++) { if (cars[i] === 'Honda') { console.log(`Found at index ${i}`); break; } else { console.log(`Visted index ${i}`); } }
Recursion
function getSum (arr:number[]):number { if (arr.length === 0) return 0; const firstVal = arr.shift(); console.log(firstVal); return firstVal + getSum(arr); } const testArr:number[] = [1, 2, 4, 5] const sum = getSum(testArr); console.log(sum);
Regex Words
const pattern = /\w+/i; const phrase = "I am legend"; const result:RegExpMatchArray | null = phrase.match(pattern) ; console.log(result?.[0]);
Regex Numbers
const pattern = /\d+/i; const phrase = "I am 23"; const result:RegExpMatchArray | null = phrase.match(pattern); console.log(result?.[0]);
Regex Test
const name = 'Bob Lee'; const regex:RegExp = new RegExp('Lee*', 'g'); const result:boolean = regex.test(name); console.log(result);
Regex Characters
const pattern = /\#+\w?/g; const phrase:string = "##I am legend##"; const result:RegExpMatchArray | null = phrase.match(pattern); console.log(result?.[0]);