标签:use TypeScript object interface Interface type class
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.
标签:use,TypeScript,object,interface,Interface,type,class 来源: https://www.cnblogs.com/Answer1215/p/16526005.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。