当前位置: 首页 > news >正文

TypeScript 接口知识点详解

TypeScript 接口知识点详解

在 TypeScript 中,接口(Interfaces)是一种强大的方式来定义对象的形状。接口可以用于定义对象的结构,同时也可以用来定义函数和类的结构。以下是 TypeScript 中接口的详细知识点:

1. 定义接口

接口是通过关键字 interface 来定义的,它描述了对象应该包含哪些属性和方法:

interface Person {name: string;age: number;
}

2. 实现接口

当一个类实现一个接口时,它必须提供接口中定义的所有属性和方法:

class User implements Person {name: string;age: number;constructor(name: string, age: number) {this.name = name;this.age = age;}
}

3. 可选属性

接口中的属性可以是可选的,使用 ? 标记:

interface Person {name: string;age?: number; // 可选属性
}

4. 只读属性

接口中的属性可以是只读的,使用 readonly 关键字标记:

interface Person {readonly id: number;name: string;
}

5. 索引签名

接口可以包含索引签名,这允许你定义一个对象,其属性是动态的,但值的类型是固定的:

interface StringArray {[index: number]: string;
}

6. 扩展接口

接口可以通过使用 extends 关键字来扩展其他接口:

interface Person {name: string;
}interface Employee extends Person {id: number;
}

7. 合并接口

接口可以被合并,这意味着你可以在不同的接口中定义相同的属性,然后合并它们:

interface Person {name: string;
}interface Person {age: number;
}let person: Person = {name: "Kimi",age: 30,
};

8. 函数类型

接口可以描述函数的形状,包括参数类型和返回值类型:

interface GreetFunction {(name: string): void;
}const greet: GreetFunction = function(name) {console.log("Hello, " + name);
};

9. 类类型

接口可以描述类的构造函数和其实例类型:

interface ClockConstructor {new (hour: number, minute: number): ClockInterface;
}interface ClockInterface {tick(): void;
}class Clock implements ClockConstructor {constructor(h: number, m: number) {}tick() {}
}

10. 接口继承类

接口可以继承类的成员,但不能继承其实现:

class Control {hello: string = "hello";
}interface SelectableControl extends Control {select(): void;
}class Button extends Control implements SelectableControl {select() {}
}

11. 接口与类型别名

虽然接口和类型别名(type aliases)都可以定义对象的形状,但它们之间有一些差异。例如,类型别名可以定义基本类型、联合类型、元组等,而接口不能。另外,接口可以被扩展,而类型别名不能。

12. 空接口

空接口不包含任何属性,它等价于 any 类型,但通常用于表示一个值可以是任何类型:

interface EmptyInterface {}function warn(user: EmptyInterface) {console.log("This is a warning message");
}

接口是 TypeScript 中定义和使用类型的一种非常灵活和强大的方式,它们为代码的结构和行为提供了清晰的约束。通过使用接口,你可以提高代码的可维护性和可读性。


http://www.mrgr.cn/news/60627.html

相关文章:

  • Files.newBufferedReader和Files.readAllLines
  • Ubuntu安装osqp-eigen最简单且一定不会出错的方法
  • 纯GO语言开发RTSP流媒体服务器-RTSP推流直播、本地保存录像、录像回放、http-flv及hls协议分发
  • 基于SSM邮票鉴赏系统的设计
  • web3对象如何连接以太网络节点
  • <项目代码>YOLOv8路面垃圾识别<目标检测>
  • 多态的体现
  • 三维测量与建模笔记 - 2.1 坐标转换基础
  • redis学习路线和内容
  • 亿赛通与Ping32:数据安全领域的两大巨擘对比
  • 二十四、Python基础语法(变量进阶)
  • 计算机网络803-(5)运输层
  • 常见大气校正模型及6S模型安装部署【20241028】
  • 仓颉编程语言一
  • 011:软件卸载工具TotalUninstall安装教程
  • 重写(外壳不变)
  • CSS3新增长度单位
  • Python自动化测试中的Mock与单元测试实战
  • 基于vue、VantUI、django的程序设计
  • 【HeadFirst 设计模式】设计模式总结与C++案例
  • 外包干了30天,技术明显退步
  • 内网穿透之网络层ICMP隧道
  • 基于SSM的宠物猫狗商业系统设计与实现
  • Chrome异步编程
  • 关于群辉920+更新升级系统后SSD固态存储不受当前DSM版本支持的解决方法
  • python实战(四)——RAG预热实践