接口(interface)
接口的作用就是为函数、对象、类,自定义类型约束。
一个简单的接口:
//简单的接口
interface FullName {
firstName: string;
secondName: string;
age?: number; //可选属性
}
//接口的应用
function fn(obj: FullName) {
console.log(
`${obj.firstName}.${obj.secondName}
年龄${obj.age || "保密"}`
);
}
//调用
fn({
firstName: "尼古拉斯",
secondName: "赵四",
});
约束函数类型的接口
//用于函数的类型接口
interface encrypt {
(key: string, value: string): string;
}
/**
* @method encrypt
* @for Function
* @param {string} key 键值
* @param {string} value 值
* @returns {string} 加密后的字符串
*/
let md5: encrypt = (key, value) => {
return key + value;
};
约束类的接口,使用implements
关键词
/**
*@class Place
*/
interface Place {
address: string;
}
/**
*@class Dogs
*/
interface Dogs {
action: string;
}
/**
*一个描述狗狗的类
*@class Dogs
*@extends Animal
*@implements Place
*@implements Dogs
*@constructor
*param {string} name 姓名
*param {string} action 行为
*param {string} address 在什么地方
*/
class Dog2 extends Animal implements Place, Dogs {
address;
name;
action;
constructor(name: string, action: string, address: string) {
super(name);
this.name = name;
this.action = action;
this.address = address;
}
eat() {
console.log(`${this.name}在${this.address}边${this.action}边吃屎`);
}
}
接口的扩展,接口也可以实现类似于类的extends
/**
* 人类
* @interface Human
*/
interface Human {
name: string;
}
/**
* 社畜
* @interface SheChu
*/
interface SheChu extends Human {
work: string;
}
/**
* 前端程序员类
* @class FontEnd
* @implements SheChu
* @constructor
* @param {string} name 姓名
* @param {string} work 工作
*/
class FontEnd implements SheChu {
name;
work;
constructor(name: string, work: string) {
this.name = name;
this.work = work;
}
}
其实,类也可以当做接口来约束类型,并且类可以实例化
/**
* @class User
* @constructor
* @param {string} username 用户名称
* @param {number} age 年龄
*/
class User {
username: string | undefined;
age: number | undefined;
constructor(username: string, age: number) {
this.username = username;
this.age = age;
}
}
/**
* @class MysqlDB
* @constructor
*/
class MysqlDB {
add(user: User): void {//将类作为参数约束,达到与interface相似的功能
console.log(user);
}
}
var user = new User("小黄", 20);
var mysql = new MysqlDB();
mysql.add(user); //{username:'小黄',age:20}
如果你还了解过typescript
的泛型,还可以进一步封装上面的模拟interface
的类
/**
* @class Artical
* @constructor
* @param {string} title 标题
* @param {string} desc 描述
*/
class Artical {
protected title: string | undefined;
protected desc: string | undefined;
constructor(title: string, desc: string) {
this.title = title;
this.desc = desc;
}
}
/**
* @class MysqlDB
* @constructor
*/
class MysqlDB {
add<T>(info: T): void {
console.log(info);
}
}
var user = new User("小黄", 20);
var artical = new Artical("这是标题", "这是描述");
var mysql = new MysqlDB();
mysql.add<User>(user); // {username:'小黄',age:20}
mysql.add<Artical>(artical); // {title:'这是标题',desc:'这是描述'}
由此达到了MysqlDB类的高度复用。