interface 是typescript核心内容,用来定义规范,无论是函数,数组或者对象,还是类都可以用接口interface来进行规范,而接口本身也是可以继承和扩展的。
interface 规范一个普通对象
// interface 规范一个普通对象
interface Person1 {
name: string;
age: number;
}
const dx: Person1 = {
name: 'dx',
age: 18,
};
interfac 可选项规范
// interfac 可选项规范 加?
interface Person2 {
name: string;
age: number;
love?: string;
}
const dx1: Person1 = {
name: 'dx',
age: 18,
};
const yx: Person2 = {
name: 'yx',
age: 18,
love: 'dx',
};
interface 规范一个对象
// interface 规范一个对象,只能是对象,不能是数组或其他
interface Object1 {
[key: string]: any;
}
const object1: Object1 = {
a: 1,
b: 2,
};
interface 规范一个数组
// interface 规范一个数组(数组也是一种对象,下标为number类型而已)
interface Array1 {
[key: number]: any;
}
const array2: Array1 = [0, 1, 2];
interface 规范一个函数
// interface 规范一个函数
interface Function1 {
// 函数接收两个参赛,key和value,都为字符串,不返回任何值 (void)
(key: string, value: string): void;
}
const function1: Function1 = (key, value) => {
console.log(key, value);
};
// 会有报错提示
// function1(1,2)
//正解
function1('dx', '永远18');
interface 规范一个类
// interface 规范一个类,有点像抽象类的作用。
interface Class1 {
name: string;
age: number;
sex: string;
love?: string;
eat(food: string): string;
}
class Class2 implements Class1 {
name: string;
age: number;
sex: string;
constructor(name: string, age: number, sex: string) {
this.name = name;
this.age = age;
this.sex = sex;
}
eat(food: string) {
return `${
this.name}吃${
food}`;
}
}
interface 接口扩展
// 接口扩展
interface Hero {
Create(name: string): void;
}
// type 继承了Hero定义的规范
interface Type extends Hero {
Position(positionName: string): void;
}
// hero1 必须满足Hero的规范和Type的规范
const hero1: Type = {
Create: (name: string) => {
console.log(`英雄的名字是${
name}`);
},
Position: (positionName: string) => {
console.log(`英雄的职业是 ${
positionName}`);
},
};
class继承加interface扩展
//疯狂套娃 继承加扩展
interface Hero {
Create(name: string): void;
}
// type 继承了Hero定义的规范
interface Type extends Hero {
Position(positionName: string): void;
}
class Master {
skill1: string;
skill2: string;
constructor(skill1: string, skill2: string) {
this.skill1 = skill1;
this.skill2 = skill2;
}
ShowAllSkills() {
console.log(this.skill1, this.skill2);
}
}
class Anqila extends Master implements Type {
constructor(skill1: string, skill2: string) {
super(skill1, skill2);
}
// 因为Type 所以必须存在
Create(name: string) {
console.log(`英雄的名字是${
name}`);
}
// 因为Type 所以必须存在
Position(positionName: string) {
console.log(`英雄的职业是 ${
positionName}`);
}
}
const anqila1 = new Anqila('技能1', '技能2');
// 来自继承
console.log(anqila1.ShowAllSkills()); //技能1 技能2
console.log(anqila1.Position('法师')) //英雄的职业是 法师
are you ok ?