09-TypeScript接口

TypeScript 有着面向对象语言所有的特性, 接口也是必不可少的一部分, 是一些属性方法的集合。

接口的作用是定义一个类的结构

接口中的属性不能有初始化的值

接口中的方法都是抽象方法, 需要由具体的类去实现

// 创建User接口
interface User {
    // 属性生命
    name: string;
    gender: string;
    age: number

    call(): void;
}

// Chinese类实现User接口
class Chinese implements User {
    name: string;
    age: number;
    gender: string;

    constructor(name: string, gender: string, age: number) {
        this.name = name;
        this.gender = gender;
        this.age = age;
    }
  
    // 实现接口的方法
    call(): void {
        console.log(`我的名字是${this.name}, 我的性别是${this.gender}, 我今年${this.age}岁`);
    }
}

let chinese = new Chinese("李小龙", "男", 18);
chinese.call();
image

你可能感兴趣的:(09-TypeScript接口)