[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 clauseextends

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 interfaceimplements.

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…

  1. 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
  2. If you need to define a type to use with the implements heritage term, it’s best to use an interface
  3. If you need to allow consumers of your types to augment them, you must use an interface.

posted @   Zhentiw  阅读(26)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源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
点击右上角即可分享
微信分享提示