抽象类
abstract关键字用于定义抽象类和在抽象类内部定义抽象方法(抽象类和类他是属于同一等级)
抽象类中的抽象方法不包含具体实现并且必须在派生类中实现。
抽象方法的语法与接口方法相似。 两者都是定义方法名但不包含方法体。
抽象类不能创建对象
父类的抽象方法,子类必须重写
abstract class Department {
constructor(public name: string) {
}
printName(): void {
console.log('Department name: ' + this.name);
}
abstract printMeeting(): void; // 必须在派生类中实现
}
class AccountingDepartment extends Department {
constructor() {
super('Accounting and Auditing'); // 在派生类的构造函数中必须调用 super()
}
printMeeting(): void {
console.log('The Accounting Department meets each Monday at 10am.');
}
generateReports(): void {
console.log('Generating accounting reports...');
}
}
let department: Department; // 允许创建一个对抽象类型的引用
department = new Department(); // 错误: 不能创建一个抽象类的实例
department = new AccountingDepartment(); // 允许对一个抽象子类进行实例化和赋值
department.printName();
department.printMeeting();
department.generateReports(); // 错误: 方法在声明的抽象类中不存在
接口
接口类型
1,属性类接口
2,函数类型接口
3,可索引接口
4,类类型接口
1,属性类接口
属性类接口就是对json数据进行限制
function getMsg(info:{label:string}){
}
相当于
interface info{
label:string;
date:number;
}
function getMsg(s:info){
}
2,函数类接口
对函数返回值进行约束,同时约束变量必须为函数
interface entryType{
(names:string):string;
}
//限制a必须是1个函数,而且具有同样的返回值的函数
let a:entryType = function():string{
return ' ';
}
3.可索引接口
用来约束对象和数组
interface userArr{
//需要1个下标为数组,值为value的类型---数组
[index:number]:string;
}
let arr:userArr = ['a','qe'];
//对象的限制
interface userArr2{
//{'names':'lisi'} key=value
//对象的索引是string 值为string
[index:string]:string;
}
let arr2:userArr2 = {names:'lisi',age:'12'}
4,类类型接口
interface classI{
names:string;
age?:number;
say():string;
}
interface classA{}
class classImp implements classI,classA{
//构造方法
//重写方法
}
interface AI{}
interface BI{}
//接口和接口的关系是继承,而且可以多继承
//类和类/抽象类之间的关系是继承,但是只能单继承
//类和接口的关系是实现,可以多实现
interface CI extends AI,BI{}
笔者作为一个新人,翻看和欣赏了大神的笔记后,自己总结加工,发表一下自己浅薄的见解,如果哪里说得不对,希望读者能提出批评和指正,本人表示诚心的感谢。
详情可以参考Typescript中文介绍