TypeScript 接口
接口描述对象、函数和索引结构而不要求必须有类,完整处理联合成员、索引签名及多接口扩展。
学完这一章,你能够
- 用对象字面量满足接口结构
- 收窄接口中的联合成员
- 初始化字典并理解接口扩展冲突
接口是结构声明,不只是抽象方法集合
interface Person { firstName: string; lastName: string; sayHi: () => string; }
const learner: Person = { firstName: "蓝色", lastName: "天空网", sayHi: () => "开始学习" };
console.log(learner.firstName, learner.lastName, learner.sayHi());
接口可描述数据属性、方法、调用签名、构造签名或索引,不要求由class实现。对象字面量也能满足结构。接口被擦除,不生成默认对象或方法实现,不能在运行时new接口或用instanceof接口。
接口的联合属性需要分支检查
interface RunOptions { program: string; commandline: string | string[] | (() => string); }
function commandText(options: RunOptions): string {
const command = options.commandline;
if (typeof command === "function") return command();
if (typeof command === "string") return command;
return command.join(" ");
}
三种输入分别是文本、文本数组和回调。读取当前成员到局部变量,再通过typeof等明确收窄;不必把成员赋给any后盲调用。回调返回类型是string,不保证没有异常,真实执行仍需定义错误策略。
数字与字符串索引签名
interface NameList { [index: number]: string; }
const names: NameList = ["教程", "工具", "资讯"];
interface Ages { [name: string]: number; }
const ages: Ages = {};
ages["学习者"] = 15;
console.log(names[0], ages["学习者"]);
只有声明var ages:Ages而未初始化就写ages["key"]会在运行时出错,注解不会创建字典。普通对象的数字键会按字符串属性规则处理,因此同时存在数字/字符串索引签名时,它们的值类型须兼容。
索引签名不保证任意键真的存在,noUncheckedIndexedAccess可让读取结果包含undefined。需要避免原型键等语义可评估Map或无原型字典,并明确输入键策略,不把所有字符串都当可信名称。
单继承、多继承和完整构造
interface PersonBase { age: number; }
interface Musician extends PersonBase { instrument: string; }
const musician: Musician = { age: 27, instrument: "Drums" };
interface First { first: number; }
interface Second { second: number; }
interface Combined extends First, Second {}
const combined: Combined = { first: 12, second: 23 };
extends可扩展多个兼容接口,冲突成员不能靠顺序自动覆盖。直接用完整对象初始化比把{}断言成Musician后逐个补字段更可靠;后者在字段尚缺少时已向检查器作出错误承诺。
可选、只读、合并及类型别名边界
interface Site { readonly domain: string; title: string; email?: string; }
interface Formatter { (site: Site): string; }
const format: Formatter = site => `${site.title} · ${site.domain}`;
readonly限制静态赋值而非冻结,email?读取可能undefined。相容的interface声明可合并,type别名不能同样重复声明;type还能表达原始联合等接口不能直接继承的结构。类implements只检查实例侧要求,不注入属性或实现。不同成员语法在函数参数兼容方面还可能有规则差异,不能把所有方法声明写法当完全同义。
完整核心源码与验证目标
展开查看收起
interface Person { firstName: string; lastName: string; sayHi: () => string; }
const learner: Person = { firstName: "蓝色", lastName: "天空网", sayHi: () => "开始学习" };
console.log(learner.firstName + learner.lastName, learner.sayHi());
interface RunOptions { program: string; commandline: string | string[] | (() => string); }
function commandText(options: RunOptions): string {
const command = options.commandline;
return typeof command === "function" ? command() : typeof command === "string" ? command : command.join(" ");
}
for (const commandline of ["hello", ["hello", "world"], () => "function result"]) console.log(commandText({ program: "mbsky", commandline }));
interface Counts { [name: string]: number; }
const counts: Counts = {}; counts["教程"] = 28; console.log(counts["教程"]);
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
- 蓝色天空网、开始学习
- 三个联合分支依次hello、hello world、function result
- 初始化后的字典读取教程为28;不使用未初始化对象
本章附件与实例包
常见错误与边界检查
- 接口不要求必须通过类实现,也不生成默认方法
- 注解不会创建索引字典对象
- 多个extends冲突不是后一个覆盖前一个
技术规范与官方资料
练习与参考解答
扩展Person增加readonly id与可选email,让两个对象字面量满足结构;再故意漏sayHi。
查看参考解答
正常对象必须有id及所有必选成员,email可省略;缺sayHi应产生结构不满足诊断。不要用as Person绕过这项练习。