TypeScript学习之——用接口来约束类(个人笔记)

用接口来约束类之间公共的能力。

interface EatAndRun {
    eat(food: string): void // 不包含具体实现
    run(distance: number): void
}
 // 用了EatAndRun接口来约束Persnon,Person里面必须含有eat和run成员,不能多也不能少
class Person implements EatAndRun {
    eat(food: string) {
        console.log('人吃' + food);
    }
    run(distance: number) {
        console.log('人跑' + distance + '米');
    }
}

class Animal implements EatAndRun {
    eat(food: string) {
        console.log('动物吃' + food);
    }
    run(distance: number) {
        console.log('动物跑' + distance + '米');
    }
}

优化


一个接口只约束一个能力(假设有另外一个类只有eat这么一个能力,用EatAndRun接口来约束是不合理的)

interface Eat {
    eat(food: string): void
}
interface Run {
    run(distance: number): void
}
class Person implements Eat, Run { // 用逗号隔开两个接口
    eat(food: string) {
        console.log('人吃' + food);
    }
    run(distance: number) {
        console.log('人跑' + distance + '米');
    }
}

class Animal implements Eat, Run {
    eat(food: string) {
        console.log('动物吃' + food);
    }
    run(distance: number) {
        console.log('动物跑' + distance + '米');
    }
}

你可能感兴趣的:(TypeScript学习之——用接口来约束类(个人笔记))