接口
接口既可以在面向对象编程中表示为行为的抽象,也可以用来描述对象的形状
我们用 interface
关键字来定义接口 在接口中可以用分号或者逗号分割每一项,也可以什么都不加
对象的形状
//接口可以用来描述`对象的形状`
interface Animal {
brak():void;
readonly age:number; // 只读类型 readonly表示只读属性 后续不可以更改
name?:string //可选类型
}
let dog:Animal={
brak(){},
name:'哈士奇', //少属性会报错
age:12,
// sex:''//多属性也会报错
}
复制代码
行为的抽象
接口可以把一些类中共有的属性和方法抽象出来,可以用来约束实现此接口的类
一个类可以实现多个接口,一个接口也可以被多个类实现
我们用 implements
关键字来代表 实现
//接口可以在面向对象编程中表示为行为的抽象
interface Brak{
say():void
}
interface Brak {
have():void
}
class Hrush implements Brak,Brak{
say(): void {
console.log('嗷嗷~');
}
have(): void{
}
}
复制代码
定义任意属性
如果我们在定义接口的时候无法预先知道有哪些属性的时候,可以使用 [propName:string]:any
,propName 名字是任意的
interface Person {
id:number,
name:string,
[propName:string]:any
}
let p ={
id:1,
name:'咸蛋超人',
age:20
}
复制代码
接口的继承
我们除了类可以继承 接口也可以继承 同样的使用 extends
关键字
interface Cat {
say(): void
}
interface typeCat extends Cat {
eat():void
}
class allCat implements typeCat {
say(): void {
console.log('喵喵~');
}
eat() {
console.log('鱼');
}
}
复制代码
函数类型接口
可以用接口来定义函数类型
interface count {
(num: number): number
}
let countNum: count = function (num: number): number {
return num * 99
}
复制代码
构造函数的类型接口
使用特殊的 new()关键字来描述类的构造函数类型
class Animal {
constructor(public name: string) {}
}
//不加new是修饰函数的,加new是修饰类的
interface WithNameClass {
new (name: string): Animal;
}
function createAnimal(clazz: WithNameClass, name: string) {
return new clazz(name);
}
let a = createAnimal(Animal, "hello");
console.log(a.name);
复制代码
实际上,在大多数的情况下使用接口类型和类型别名的效果等价,但是在某些特定的场景下这两者还是存在很大区别。
基础数据类型 与接口区别
1.基础数据类型 与接口不同,类型别名还可以用于其他类型,如基本类型(原始值)、联合类型、元组
// primitive
type Name = string;
// union
type PartialPoint = PartialPointX | PartialPointY;
// tuple
type Data = [number, string];
// dom
let div = document.createElement("div");
type B = typeof div;
复制代码
2.重复定义
接口可以定义多次 会被自动合并为单个接口 类型别名不可以重复定义
interface Point {
x: number;
}
interface Point {
y: number;
}
const point: Point = { x: 1, y: 2 };
复制代码
3.扩展 接口可以扩展类型别名,同理,类型别名也可以扩展接口。但是两者实现扩展的方式不同 接口的扩展就是继承,通过 extends 来实现。类型别名的扩展就是交叉类型,通过 & 来实现。
// 接口扩展接口
interface PointX {
x: number;
}
interface Point extends PointX {
y: number;
}
// ----
// 类型别名扩展类型别名
type PointX = {
x: number;
};
type Point = PointX & {
y: number;
};
// ----
// 接口扩展类型别名
type PointX = {
x: number;
};
interface Point extends PointX {
y: number;
}
// ----
// 类型别名扩展接口
interface PointX {
x: number;
}
type Point = PointX & {
y: number;
};
复制代码
4.实现 这里有一个特殊情况 类无法实现定义了联合类型的类型别名
type PartialPoint = { x: number } | { y: number };
// A class can only implement an object type or
// intersection of object types with statically known members.
class SomePartialPoint implements PartialPoint {
// Error
x = 1;
y = 2;
}
复制代码