Skip to content

Instantly share code, notes, and snippets.

@nguyentien98
Last active October 31, 2018 07:27
Show Gist options
  • Save nguyentien98/11fb0967d6efced068c75e861879a337 to your computer and use it in GitHub Desktop.
Save nguyentien98/11fb0967d6efced068c75e861879a337 to your computer and use it in GitHub Desktop.

Kiểu dữ liệu

  1. String:
let color: string = "blue";
  1. Number:
let age: number = 37;
  1. Array: Đặt kiểu dữ liệu cho các elements trong array
let numbers: number[] = [1, 2, 3];
let numbers : Array<number> = [];

Kiểu gì cũng được

let anyList : Array<any> = [];
  1. Kiểu Tuple

Tạo ra array với số element và kiểu element chỉ định sẵn

// Declare a tuple type
let x: [string, number];
// Initialize it
x = ["hello", 10]; // OK
// Initialize it incorrectly
x = [10, "hello"]; // Error
x = ["hello", 10, 15];
  1. Kiểu any Kiểu này giúp cho biến được khai báo có thể nhận bát cứ kiểu dữ liệu nào.
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false;

Kiểu any cho array

let anyList : Array<any> = [];
  1. Kiểu void

Hàm được khai báo kiểu này tức là sẽ không trả về giá trị gì hoặc chỉ được trả về undefined hoặc null:

function test() : void {
    return undefined;
}
function test() : void {
    return null;
}
function test() : void {
    alert('Hihi');
}
  1. Kiểu Null và Undefined Như tên của nó

  2. Kiểu object

function create(o: object | null): void;

create({ prop: 0 }); // OK
create(null); // OK

create(42); // Error
create("string"); // Error
create(false); // Error
create(undefined); // Error

**Ta có thê dùng | để khai báo nhiều kiểu dữ liệu cho biến:

function test(name: string | number) { 
} // Cho function

let test: string | number = 'd'; // Cho biến

OOP

Interface

Class

  1. super Đây là từ khóa dùng để gọi đến phương thức hoặc thuộc tính của lớp cha.

  2. readonly Đây là từ khóa để khai báo rằng thuộc tính nào đó chỉ có thể được thay đổi bằng hàm khởi tạo. Bất cứ phương thức trong class hay ngoài class đều không được quyền thay đổi.

class Octopus {
    readonly name: string;
    constructor (theName: string) {
        this.name = theName;
    }
    setName(theName: string) {
        this.name = theName;
    } // Error
}
let dad = new Octopus("Man with the 8 strong legs");
dad.name = "Man with the 3-piece suit"; // error! name is readonly.
  1. Get và Set trong class(Accessors) Hai từ khóa này để khai báo các hàm getter/setter cho thuộc tính nào đó. Ta có thể dùng để gán cũng như lấy giá trị cho các thuộc tính private/protected đó.
class Employee {
    private __fullName: string;

    get fullName(): string {
        return this.__fullName;
    }

    set fullName(newName: string) {
        this.__fullName = newName;
    }
}

let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
    console.log(employee.fullName);
}
  1. Static Từ khóa này dùng để khai báo các phương thức cũng như các thuộc tính static. Ta có thể gọi đến cá phương thức và các thuộc tính này mà không cần khởi tạo object.
class Employee {
    static fullName: string = 'Tiến Nguyễn';

    static sayHello() {
        alert('Hello');
    }
}

console.log(Employee.name);
Employee.sayHello();
  1. Abstract Cũng giống như hàm abstract trong PHP.
abstract class Department {

    constructor(public name: string) {
    }

    printName(): void {
        console.log("Department name: " + this.name);
    }

    abstract printMeeting(): void; // must be implemented in derived classes
}

class AccountingDepartment extends Department {

    constructor() {
        super("Accounting and Auditing"); // constructors in derived classes must call super()
    }

    printMeeting(): void {
        console.log("The Accounting Department meets each Monday at 10am.");
    }

    generateReports(): void {
        console.log("Generating accounting reports...");
    }
}


let department: Department; // ok to create a reference to an abstract type
department = new AccountingDepartment(); // ok to create and assign a non-abstract subclass
department.generateReports(); // Bởi vì bên trên ta đã khai báo biến department thuộc kiểu dữ liệu là Department. Mà trong abtract Department không có phương thức generateReports(). Ch
  1. Interface kế thừa class

Trong typescipt thì interface có thể kế thừa lại 1 class. Điều này có nghĩa là interface đó sẽ tự lấy tên các phương thức của class cha để cho vào chính nó.

class AccountingDepartment {
    printMeeting(): void {
        console.log("The Accounting Department meets each Monday at 10am.");
    }

    generateReports(): void {
        console.log("Generating accounting reports...");
    }
}

interface Department extends AccountingDepartment {

}
  1. Interface kế thừa interface
interface Department {
    name: string;
}

interface Department2 extends Department {
    age: number;
}

// Ta phải khai báo cả 2 thuộc tính của cả 2 interface
class X implements Department2 {
    name: string = 'hihi';
    age: number = 15;
}

Từ khóa this

Nếu như tạo 1 hàm trong 1 phương thức của lớp, từ khóa this trong hàm đó sẽ bị chuyển thành window và ko còn là của class hiện tại nữa. Ví dụ

var  age = 5;
class X {
    age: number = 18;
    growUp() {
        let tien = function () {
            this.age++;
        }
        tien();
    }
}

var x = new X();
x.growUp();
console.log(age); // 6
console.log(x.age); // 18

Các giải quyết

  1. Gán this bằng biến khác trước khi tạo hàm
class X {
    age: number = 18;
    growUp() {
        let that = this.
        let tien = function () {
            that.age++;
        }
        tien();
    }
}

var x = new X();
x.growUp(); // Hoạt động bình thường
console.log(x.age); // 19
  1. Dùng hàm rút gọn Hàm rút gọn (arrow function) sẽ không tạo ra this của riêng nó.
class X {
    age: number = 18;
    growUp() {
        let tien = () => {
            this.age++;
        }
        tien();
    }
}

var x = new X();
x.growUp();
console.log(x.age);

for..in và for..of

  1. For..of

Dùng để lặp lấy giá trị của 1 mảng:

let someArray = [1, "string", false];

for (let entry of someArray) {
    console.log(entry); // 1, "string", false
}
  1. For..in Dùng để lặp và lấy ra key của mảng
let list = [1, "string", false];

for (let i in list) {
   console.log(i); // "0", "1", "2",
}

Đồng thời nó cũng dùng để lấy ra property name của object:

let lits = {
    name: 'Tien',
    age: 18
};

for(let e in array) {
    console.log(array[e]); // name, age
}

Module

Export và import

  1. Export Ta có thể import 1 hoặc nhiều class, interface, function, const... trong javascript. Nhưng trước tiên ta cần phải export chúng ra.

Ví dụ export 2 interface

export interface Human {
    name: string;
    age: number;
    height?: number;
}
export interface Animal {
    name: string;
    age: number;
    height?: number;
}

Sau đó ta có thể import vào class khác để sử dụng

import { Human, Dog } from './interface/HumanInterface';

class Asian implements Human {
    name: string = 'Tien';
    age: number = 20;
}

class Dog implements Animal {
    name: string = 'Milu';
    age: number = 20;
}
  1. Export default

Trong 1 file ta chỉ có thể export default 1 lần. Khi đó nếu import từ bên ngoài thì mặc định nó sẽ được export ra.

Ví dụ export 2 interface có default

export default interface Human {
    name: string;
    age: number;
    height?: number;
}
export interface Animal {
    name: string;
    age: number;
    height?: number;
}

Ở file khác:

import Human from './interface/HumanInterface';
import { Dog } from './interface/HumanInterface';

class Asian implements Human {
    name: string = 'Tien';
    age: number = 20;
}

class Dog implements Animal {
    name: string = 'Milu';
    age: number = 20;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment