# TypeScript 对象

# 1. 类的定义

class Employe {
    private name: string 		// 私有属性
    public salary: number		// 公开属性

    // 类中的 property 必须被初始
    constructor(name: string, salary: number){
        this.name = name
        this.salary = salary
    }
}

const emp1 = new Employe('hedon', 8000)
console.log(emp1)

简便:

class Employe {
    // 在 constructor 中加上 public 和 private
    // 编译器就会帮我们给这个类加上对应的 property
    constructor(public name: string, public salary: number){
        this.name = name
        this.salary = salary
    }
}

# 2. setter&getter

class Employe {

    private allocatedBonus?: number

    constructor(public name: string, public salary: number){
        this.name = name
        this.salary = salary
    }

    // setter/getter
  	// 名字不能跟属性名一样
    set bonus(v: number) {
        this.allocatedBonus = v
    }
    get bonus() {
        return this.allocatedBonus || 0
    }
}

# 3. 类的继承

class Employe {
    constructor(public name: string, public salary: number){
        this.name = name
        this.salary = salary
    }
}

// 继承
class Manager extends Employe {
  	// Employe 有的 Manager 都有
  
  	// 子类独有的属性
    private reporters: Employe[] = []
    addRepeorter(e: Employe) {
        this.reporters.push(e)
    }
    get reportersList(){
        return this.reporters
    }
}

# 4. 实现接口

  • 不需要显式 implements(也可以显式 implements)
  • 把接口中该有的东西都实现了,就自然实现了该接口
interface Employee {
    name: string
    salary: number
    bonus: number
}

// EmployeeImpl 不需要显式 implements Employee
// 只要 EmployeeImpl 中有 Employee 该有的
// 那它就是实现了 Employee
// 这一点跟 Go 非常像
class EmployeeImpl {
    public allocatedBonus?: number
    constructor(public name: string, public salary: number) {
        this.name = name
        this.salary = salary
    }
    set bonus(v: number) {
        this.allocatedBonus = v
    }
    get bonus(){
        return this.allocatedBonus || 0
    }
}

class Manager extends EmployeeImpl {
    private reporters: EmployeeImpl[] = []
    addReporter(e: EmployeeImpl) {
        this.reporters.push(e)
    }
}

const empImpl = new EmployeeImpl('hedon', 2000)
const emp1: Employee = empImpl                          //ok
const emp2: Employee = new Manager('hedon', 40000)      //ok
上次更新: 11/5/2021, 4:06:48 PM