typescript 关于类的几个概念

206 阅读1分钟

泛型

// 泛型 : 参数化的类型 , 一般用来限制集合的内容
class Person {
  constructor(public name: string) {}
}

let workers: Array<Person> = [];

workers[0] = new Person("xiaoming");

workers[1] = 1; // 报错 

接口

// 接口 : 用来建立某种代码的约定

// 第一种用法

interface IPerson {
  name: string;
  age: number;
}

class Person1 {
  constructor(public config: IPerson) {}
}

let p5 = new Person1({
  name: "西行记",
  age: 500
});
console.log(p5); // Person1 { config: { name: '西行记', age: 500 } }

// 第二种使用方式

interface Animal {
  eat();
}

class Sheep implements Animal { // 实现这个接口的类必须要实现这个方法
  eat(){
    console.log('我吃草');
  }
}

class Tiger implements Animal {
  eat(){
    console.log('我吃肉');
  }
}