4.5 Class, Type, Interface - quan1997ap/angular-app-note GitHub Wiki
I. Class
Khai báo
Property: Các thuộc tính
constructor: Khởi tạo giá trị cho đối tượng
class Avenger {
name: string;
weapon: string;
constructor(_name: string, _weapon: string) {
this.name = _name;
this.weapon = _weapon;
}
attack() {
console.log(`I’m ${this.name} who can attack with ${this.weapon}`);
}
}
const IronMan = new Avenger('Iron Man', 'lazer');
1.1 Tính kế thừa (inheritance) class
class InfinityWar extends Avenger {
attack() {
super.attack();
console.log('I love 3000');
}
}
1.2 Access modifier: Public, private, protected
Với private, property không thể bị gọi từ ngoài vào.
Với protected, nó giống với private với 1 ngoại lệ là các property này có thể được gọi tới từ bên trong lớp con kế thừa từ lớp cha.
public name: string;
private weapon: string;
II. INTERFACE
Default:
interface accountConfig{
name?: string;
password?: string;
}
function createAccount(config: accountConfig) {
let newAccount = { name: 'Tran Ngoc Tan', password: 'qwe123' }
if (config.name) { newCar = config.name }
if (config.password) { newCar = config.password }
return newAccount;
}
...
let newAccount = createAccount({ name: 'Ribi Sachi' });
Function type trong interface:
interface IRun {
(speed: numeric, destination: string): numeric;
}
let runner: IRun;
runner = function(speed: numeric, destination: string): numeric {
// ... implement nội dung function
}
III. TYPE
IV. So sánh
- Chỉ sử dụng Class khi ta có logic nghiệp vụ thực sự cần được implement để thực thi.
- Ngược lại, nếu chỉ dùng nó để tạo 1 ràng buộc kiểu cho params hay variable, ta nên dùng Interface.
- Interface trong Typescript sẽ chỉ có vai trò nhắc hint, báo lỗi khi viết code bằng editor cũng như trong quá trình compile. Sau đó, nó sẽ được loại bỏ khỏi mã đích javascript.
- Ngược lại, không giống như interface, một class của Typescript sẽ sinh ra 1 Javascript construct thực sự, làm tăng dung lượng mã đích.
- Type vs Interface