[TypeScript] Interface
2022/7/27 23:23:17
本文主要是介绍[TypeScript] Interface,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
An interface is a way of defining an object type. An “object type” can be thought of as, “an instance of a class could conceivably look like this”.
For example, string | number
is not an object type, because it makes use of the union type operator.
Inheritance in interfaces
EXTENDS
If you’ve ever seen a JavaScript class that “inherits” behavior from a base class, you’ve seen an example of what TypeScript calls a heritage clause: extends
class Animal { eat(food) { consumeFood(food) } } class Dog extends Animal { bark() { return "woof" } } const d = new Dog() d.eat d.bark
- Just as in in JavaScript, a subclass
extends
from a base class. - Additionally a “sub-interface”
extends
from a base interface, as shown in the example below
IMPLEMENTS
TypeScript adds a second heritage clause that can be used to state that a given class should produce instances that confirm to a given interface: implements
.
interface AnimalLike { eat(food): void } class Dog implements AnimalLike { // Error: Class 'Dog' incorrectly implements interface 'AnimalLike'. // Property 'eat' is missing in type 'Dog' but required in type 'AnimalLike'. bark() { return "woof" } }
Open Interfaces
TypeScript interfaces are “open”, meaning that unlike in type aliases, you can have multiple declarations in the same scope:
You may be asking yourself: where and how is this useful?
Imagine a situation where you want to add a global property to the window
object
window.document // an existing property window.exampleProperty = 42 // tells TS that `exampleProperty` exists interface Window { exampleProperty: number }
What we have done here is augment an existing Window
interface that TypeScript has set up for us behind the scene.
Choosing which to use
In many situations, either a type
alias or an interface
would be perfectly fine, however…
- If you need to define something other than an object type (e.g., use of the
|
union type operator), you must use a type alias - If you need to define a type to use with the
implements
heritage term, it’s best to use an interface - If you need to allow consumers of your types to augment them, you must use an interface.
这篇关于[TypeScript] Interface的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-04安装 VPrix Desktop 的系统要求-icode9专业技术文章分享
- 2024-05-01巧用 TiCDC Syncpoint 构建银行实时交易和准实时计算一体化架构
- 2024-05-01银行核心背后的落地工程体系丨Oracle - TiDB 数据迁移详解
- 2024-04-26高性能表格工具VTable总体构成-icode9专业技术文章分享
- 2024-04-16软路由代理问题, tg 无法代理问题-icode9专业技术文章分享
- 2024-04-16程序猿用什么锅-icode9专业技术文章分享
- 2024-04-16自建 NAS 的方案-icode9专业技术文章分享
- 2024-04-14ansible 在远程主机上执行脚本,并传入参数-icode9专业技术文章分享
- 2024-04-14ansible 在远程主机上执行脚本,并传入参数, 加上remote_src: yes 配置-icode9专业技术文章分享
- 2024-04-14ansible 检测远程主机的8080端口,如果关闭,则echo 进程已关闭-icode9专业技术文章分享