A minimalist typescript cheatsheet to get started quickly
// Install typescript
npm install -g concurrently lite-server typescript
// Run the .ts
tsc typescript-cheatsheet --watch
// In another terminal window
node typescript-cheatsheet
export {}; | |
let message = "Hello"; | |
console.log(message); | |
let isBeginner: boolean = true; | |
let total: number = 0; | |
let name: string = "Joe"; | |
let sentence: string = `My name is ${name}`; | |
console.log(sentence); | |
let list01: number[] = [1, 2, 3]; | |
let list02: Array<number> = [1, 2, 3]; | |
let person01: [string, number] = ["Bob", 30]; | |
enum Color { | |
Reg, | |
Green, | |
Blue | |
} | |
let c: Color = Color.Green; | |
console.log(c); | |
let myVariable: any = 10; | |
function hasName(obj: any): obj is { name: string } { | |
return !!obj && typeof obj === "object" && "name" in obj; | |
} | |
if (hasName(myVariable)) { | |
console.log(myVariable.name); | |
} | |
let multiType: number | boolean; | |
multiType = 10; | |
multiType = true; | |
function add(num1: number, num2?: number): number { | |
return num1 + num2; | |
} | |
add(5); | |
function fullName(person: { firstName: string; lastName: string }): void { | |
console.log(person.firstName, person.lastName); | |
} | |
let p = { | |
firstName: "Bob", | |
lastName: "Dylan" | |
}; | |
fullName(p); | |
interface Person { | |
firstName: string; | |
lastName: string; | |
address?: string; | |
} | |
function user(person: Person): void { | |
console.log(person.firstName, person.lastName); | |
} | |
user({ firstName: "Johnny", lastName: "Cash" }); | |
class Employee { | |
employeeName: string; | |
// public employeeName: string; // full access | |
// private employeeName: string; // no access | |
// protected employeeName: string; // acess within a derived class | |
constructor(name: string) { | |
this.employeeName = name; | |
} | |
greet() { | |
console.log("Good morning", this.employeeName); | |
} | |
} | |
let emp1 = new Employee("Kenny"); | |
console.log(emp1.employeeName); | |
emp1.greet(); | |
class Manager extends Employee { | |
constructor(managerName: string) { | |
super(managerName); | |
} | |
delegateWork() { | |
console.log("Manager delegating tasks"); | |
} | |
} | |
let m1 = new Manager("Bruce"); | |
m1.delegateWork(); | |
m1.greet(); | |
console.log(m1.employeeName); |