接口
在TS里面接口可以定义任何类型,接口就是一种数据规范,用于定义对象的结构契约,编译后会被擦除,不影响运行时候的性能
基本用法
- 关键字 interface
interface Person {
name: string;
}
const PersonOne: Person = {
name: "哈哈哈",
};
- 可选属性
一般用?来表示可选属性,可有可无
interface Person2 {
name: string;
color?: string;
}
const Man: Person2 = {
name: "哈哈",
};
绕开多余属性检查
有的时候我们不希望 Typescript 这么严格的对数据检查,我们需要绕开多余性检查
使用?变成可选属性
interface Vegetables {
color?: string;
type: string;
}
const VegetablesResult: Vegetable = {
type: "哈哈哈",
};
使用索引签名
interface Vegetables {
color: string;
type: string;
[prop: string]: any;
}
const food = {
color: "red",
type: "水果",
price: 30,
};
只读属性
接口设置为只读属性
interface Role {
readonly name: string;
readonly xingbie: string;
}
const shili: Role = {
name: "今天",
xingbie: "男",
};
shili.name = "明天"; //报错误
函数类型
接口类型还可以描述函数
interface AddFunc {
(num1: number, num2: number): number;
}
const add2: AddFunc = (arg1: number, arg2: number) => {
return arg1 + arg2;
};
接口类型里面除了函数还可以有其他的类型
interface Func {
(num1: number, num2: number): number;
}
interface typeAddson {
id: number;
type: string;
add: Func;
}
const typeResult: typeAddson = {
id: 1,
type: "哈哈",
add: (arg1, arg2) => {
return arg1 + arg2;
},
};
typeResult.addPosition(1, 2);
接口的高阶用法
索引签名
索引签名可以用来描述对象的属性,也可以用来描述数组的元素
interface RoleDic {
readonly [id: number]: string;
}
const role: RoleDic = {
0: "super_admin",
};
role[0] = "Hello"; //error 类型报错误 因为readonly只读
接口继承
接口和接口的继承 extends
interface Person {
name: string;
}
interface Man extends Person {
xingbie: string;
}
const Man_People: Man = {
name: "哈哈哈",
xingbie: "男",
};
接口和类的继承 extends
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
printname() {
return this.name;
}
}
interface Man extends Person {
xingbie: string;
}
const Man_People: Man = {
name: "哈哈哈",
xingbie: "男",
printname: () => {
return Man_People.name;
},
};
console.log(Man_People.printname());
类继承接口 implements
interface Man {
xingbie: number;
}
class Person implements Man {
name: string;
xingbie: number;
constructor(name: string, xingbie: number) {
this.name = name;
this.xingbie = xingbie;
}
printname() {
return this.name;
}
printxingbie() {
return this.xingbie;
}
}
const Person2 = new Person("哈哈哈", 123);
console.log(Person2.printname());
console.log(Person2.printxingbie());