跳到主要内容

TypeScript interface 关键字介绍

· 阅读需 4 分钟

interface 用于定义对象类型函数签名类结构等。

基础语法

interface User {
name: string;
age: number;
isAdmin?: boolean; // 可选属性(Optional)
readonly id: number; // 只读属性
}
  • ? 表示非必须
  • readonly 表示只读

函数类型

  1. 定义了一个函数签名,参数是 source keyword,返回值是 boolean 类型。
  2. 声明了一个 search 常亮,并赋值了一个箭头函数。
interface SearchFunc {
(source: string, keyword: string): boolean;
}

// src, kw 名称不需要与函数类型定义中一致,但参数类型需要一致。
const search: SearchFunc = (src, kw) => src.includes(kw);

使用场景

约束回调函数

interface ClickHandler {
(event: MouseEvent, context: HTMLElement): void;
}

const handleClick: ClickHandler = (e, element) => {
console.log("Clicked on:", element.tagName);
};

统一 API 请求函数

interface ApiRequest {
(url: string, params: Record<string, string>): Promise<Response>;
}

const fetchData: ApiRequest = async (path, data) => {
return await fetch(path, { body: JSON.stringify(data) });
};

高阶函数参数

function higherOrderFunc(callback: SearchFunc) {
callback("Hello", "H"); // 调用时必须传入符合签名的函数
}

higherOrderFunc((s, k) => s.startsWith(k));

可索引类型

// 数组类型
interface StringArray {
[index: number]: string; // 索引为数字,值为字符串
}

// 字典类型
interface NumberDictionary {
[key: string]: number; // 键为字符串,值为数字
length: number; // 明确声明的属性必须符合索引签名
}

使用案例:

// 用索引获取数组元素
interface StudentArray {
[index: number]: string;
}

let studentArr: StudentArray = ["Bob", "Fred"];
let student1: string = studentArr[0]; // 'Bob'
let student2: string = studentArr[1]; // 'Fred'

// 用索引获取对象属性
interface StudentObject {
[key: string]: number;
}

let studentObj: StudentObject = {};
studentObj['Bob'] = 1;
studentObj['Fred'] = 2; // { Bob: 1, Fred: 2 }

继承与扩展

interface Animal {
name: string;
}

interface Dog extends Animal {
breed: string;

bark(): void;
}

// 多重继承
interface SuperDog extends Dog {
fly(): void;
}

类实现接口

interface ClockInterface {
currentTime: Date;

setTime(d: Date): void;
}

class Clock implements ClockInterface {
currentTime: Date = new Date();

setTime(d: Date) {
this.currentTime = d;
}
}

混合类型

interface Counter {
(start: number): string; // 函数签名
interval: number; // 属性
reset(): void; // 方法
}

// 实现示例
function createCounter(): Counter {
let counter = function (start: number) {
} as Counter;
counter.interval = 5;
counter.reset = () => {
};
return counter;
}

接口合并

interface Box {
width: number;
}

interface Box {
height: number;
}

// 合并后等价于:
interface Box {
width: number;
height: number;
}

动态扩展接口

interface Window {
myCustomProp: string; // 扩展全局 Window 类型
}

泛型接口

interface ApiResponse<T> {
code: number;
data: T;
message?: string;
}

// 使用
const userResponse: ApiResponse<User> = {
code: 200,
data: {name: "Alice", age: 30}
};