TypeScript 接口深入 — 函数类型与索引签名
接口定义函数类型、可索引类型、类实现接口 · 难度:进阶 · +20XP
接口能定义的不只是对象
interface 还能定义函数、数组、类的形状。
函数接口
// 定义一个搜索函数(接收字符串,返回布尔值)
interface SearchFunc {
(source: string, keyword: string): boolean;
}
const mySearch: SearchFunc = (src, kw) => {
return src.includes(kw);
};
索引签名 — 动态属性名
interface StringMap {
[key: string]: string; // 任意字符串属性名,值都是 string
}
const colors: StringMap = {
red: "#ff0000",
green: "#00ff00",
blue: "#0000ff",
primary: "#2196F3"
};
类实现接口
interface Clock {
currentTime: Date;
tick(): void;
}
class DigitalClock implements Clock {
currentTime = new Date();
tick() {
this.currentTime = new Date();
console.log(this.currentTime);
}
}