接口概念
“接口”是一种定义类型结构的方法,它描述了一个类型应该具有的属性、方法和索引签名。
接口的基本定义
接口允许你定义一个类型应该有的结构。这种结构可以包括:
- 属性(Properties):描述对象应该拥有的字段。
- 方法(Methods):描述对象应该能够执行的行为。
- 索引签名(Index Signatures):允许你定义对象如何通过索引访问其成员。
- 可选属性(Optional Properties):通过在属性名后添加
?
符号来标记属性为可选。 - 只读属性(Readonly Properties):通过在属性前添加
readonly
关键字来定义不可修改的属性。
接口的语法
interface InterfaceName {
// 属性
property: Type;
// 方法
method(arg1: Type, arg2: Type): ReturnType;
}
接口的应用
接口可以应用于多种场景,例如:
- 类:类可以实现一个或多个接口,确保类具备某些特定的结构。
- 对象字面量:可以用接口来验证一个对象字面量是否具有预期的结构。
- 函数参数:接口可以用来定义函数参数的结构。
- 泛型约束:接口可以用来定义泛型函数或类的参数类型约束。
interface arrLength { length: number } function arrLengthFun<t extends arrLength>(params: t): t { return params } console.log('arrLengthFun', arrLengthFun([1, 2, 3, 4, 6]).length);
接口继承
接口之间也可以进行继承,一个接口可以从另一个接口继承属性和方法:
interface Shape {
color: string;
}
interface Square extends Shape {
length: number;
}
const square: Square = { color: "blue", length: 10 };
接口实现implements
通过接口集合implements来限制类,必须要有的某些属性和方法。
interface CanEat {
eat(food: string): void;
}
class Animal implements CanEat {
eat(food: string): void {
return food
}
}
const animal = new Animal();
animal.eat("grass");
泛型接口
泛型接口允许你在接口定义中使用泛型参数,使得接口可以根据不同的类型参数来适应不同的类型需求。
interface GenericInterface<T> {
value: T;
}
// 使用泛型接口
const obj: GenericInterface<string> = { value: "hello" };
interface Food<T> {
id: (value: T) => T
idArr: () => T[]
}
let foodFun: Food<number> = {
id(value: number) {
return value
},
idArr() {
return [1, 2, 3]
}
}
console.log('foodFun',foodFun.id(111))
console.log('foodFun',foodFun.idArr())
interface GenericFunction<T, R> {
process: (value: T) => R;
}
class DataProcessor implements GenericFunction<number, string> {
process(value: number): string {
return value.toString();
}
}
const processor: GenericFunction<number, string> = new DataProcessor();
console.log(processor.process(123)); // 输出 "123"
充盈美满