Skip to content

Instantly share code, notes, and snippets.

@whal-e3
Created September 9, 2021 03:08
Show Gist options
  • Save whal-e3/b852902bb675ac3269d2571d41bc2859 to your computer and use it in GitHub Desktop.
Save whal-e3/b852902bb675ac3269d2571d41bc2859 to your computer and use it in GitHub Desktop.
TypeScript Basics
let id: number = 5;
let company: string = "Eric";
let isBool: boolean = true;
let x: any = 2;
x = false;
let ids: number[] = [1, 2, 3, 4, 5];
let arr: any[] = [1, true, "asf"];
// Tuple (fixed number of elements and types)
let person: [number, string, boolean] = [1, "3", true];
let employee: [number, string][];
employee = [
[1, "brad"],
[2, "Eric"],
];
// Union
type Point = number | string;
let pid: string | number = "324";
// Enum
enum Direction1 {
Up = 1,
Down,
Left,
Right,
}
enum Direction2 {
Up = "Up",
Down = "Down",
Left = "Left",
Right = "Right",
}
// Objects
type User = { id: number; name: string };
const user: User = {
id: 1,
name: "John",
};
// Type Assertion
let cid: any = 1;
// let customerId = <number>cid;
let customerId = cid as number;
// Functions
function addNum(x: number, y: number): number {
return x + y;
}
function log(message: string | number): void {
console.log(message);
}
// Interface
interface UserInterface {
readonly id: number;
name: string;
age?: number;
}
const user1: UserInterface = {
id: 1,
name: "John",
};
// interface for function
interface Mathfunc {
(x: number, y: number): number;
}
const add: Mathfunc = (x: number, y: number): number => x + y;
const sub: Mathfunc = (x: number, y: number): number => x - y;
// Classes
interface PersonInterface {
name: string;
register(): string;
}
class Person implements PersonInterface {
private id: number;
protected pid: number;
name: string;
constructor(id: number, pid: number, name: string) {
this.id = id;
this.pid = pid;
this.name = name;
}
register() {
return `ID ${this.id} : ${this.name} is now registered`;
}
}
const eric = new Person(1, 424, "eric");
const mike = new Person(2, 4354, "Mike");
console.log(eric.register());
// sub-Class
class Employee extends Person {
position: string;
constructor(id: number, pid: number, name: string, position: string) {
super(id, pid, name);
this.position = position;
}
}
const emp = new Employee(3, 3244, "shawn", "Dev");
console.log(emp.register());
// Generics
function getArray<T>(items: T[]): T[] {
return new Array().concat(items);
}
let numArray = getArray<number>([1, 2, 3, 4]);
let strArray = getArray<string>(["brad", "john", "jill"]);
numArray.push(3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment