[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.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2020-07-27 [Express 5] Create a express 5 application with node 14
2020-07-27 [Bash] Batch Rename Every File in a Directory with zsh
2020-07-27 [Angular] Angular Router Extra Options - Recommended Settings
2020-07-27 [CSS 3 + JS] Create a Function to Convert JS Numbers into CSS Hex Colors
2020-07-27 [Express] Handle Syncronous and Asyncronous Errors in Express
2019-07-27 [RxJava] Mapping
2018-07-27 [JavaEE] JTA, Java Transaction API, Repository for DB opreations