接口之间叫继承(extends) 类和接口之间叫实现(implements)
基础定义接口
interface IPerson {
// id 只读属性
readonly id : number
// name、age 必须有
name: string
age: number
// sex 可有可无 加?
sex?: string
}
常用接口定义方法
interface IType {
[key: string]: string;
}
interface Form {
"username": string,
"nickName": string,
"email": string,
"password": string,
"phone": string,
"companyName": string,
"position": string,
// 定义一个数组,数组中元素为 对象
"roles": IType[],
// 通用类型设计
[key: string]: any;
}
const ruleForm: Form = reactive({
"username": "",
"email": "",
"nickName": "",
"password": "",
"phone": "",
"position": "",
"companyName": "",
"roles": [],
});
//通过接口限定函数类型
interface ISrearchFun {
(source: string, subString: string): boolean
}
//实现
const search: ISrearchFun = function (source: string, subString: string): boolean{
return source.search(subString) > 1
}
// 调用
console.log('今天星期四','四')
类的类型
interface IFly{
fly()
}
// 定义类 实现上面接口
class Person implements IFly{
// 必须有接口中的方法
fly(){
console.log('我飞了!');
}
}
// 实例化
const person = new Person();
person.fly();
// 实现多个接口
interface ISwim{
swim()
}
class Person2 implements IFly,ISwim{
// 必须有接口中的方法
fly(){
console.log('我飞了!');
}
swim(){
console.log('我游泳!');
}
}
// 实例化
const person2 = new Person2();
person2.fly();
person2.swim();
// 将多类型整合 一次实现
class Sports implements IFly,ISwim{ }
class Person3 implements Sports {
// 必须有接口中的方法
fly(){
console.log('我飞了!');
}
swim(){
console.log('我游泳!');
}
}
const person3 = new Person3();
person3.fly();
person3.swim();
网友评论