当前位置:网站首页>The difference between TS Gymnastics (cross operation) and interface inheritance
The difference between TS Gymnastics (cross operation) and interface inheritance
2022-07-06 07:29:00 【Jioho_】
TS Artistic Gymnastics &( Crossover operation ) and The difference between interface inheritance
Cross type and Interface inheritance is merged 2 The role of objects , However, there are still many things to pay attention to in actual use
& Cross type
& Also known as Cross type (Intersection types)
, Through the first demo Get to know
type Todo1 = {
name: string
}
type Todo2 = {
description: string
}
type Todo = Todo1 & Todo2
In the above demo in
Type derivation display :type Todo = Todo1 & Todo2
The actual effect :type Todo = { name:string; description: string }
situation 2
type NumberAndString = string & number // never
type Todo1 = {
id: string
title: string
do(title: string, status: boolean): void
fn(): void
}
type Todo2 = {
id: number
title: string | number
do(title: string, id: number, status: boolean): void
fn(): void
}
type Todo = Todo1 & Todo2
let todo: Todo = {
id: 'string', // Report errors Type 'string' is not assignable to type 'never'.
id: 1234, // Report errors Type 'number' is not assignable to type 'never'.
title: 'title' // Can only be merged into string type
do(title:string,status:boolean){
},
fn(){
}
}
NumberAndString The result of type derivation of is never, Because there is no value that is string again number Of .
and Todo The result of type derivation is the same ,id Equal to any value is wrong ( the reason being that never). about title
Come on string & string | number
When , In fact, or string
do Because it is a function type , Even if the parameters are different, they cannot be merged ( Errors will be reported when using ), and fn Because the functions are the same , Merge naturally
Come to a conclusion
- & The cross type is 2 Types of Combine . It is what both sides have that can be merged , Different ones will be excluded
- If you exclude the same thing in the end , Then it will change never type ( That is, the type does not exist )
- Built in type (string,number,boolean,unio Joint type ) You can use &
interface( Interface ) Inheritance
Interface inheritance and The biggest difference between cross types is
Cross type can be in Customize type、 The original type (string,number,boolean…) 、 Joint type (string | number)、 Even Interface Cross each other
Interface crossing also follows & The rules of , Like the one below demo,id Still cross for never type
interface ITodo {
id: string
title: string
do(title: string, status: boolean): void
fn(): void
}
interface ITodo2 = {
id: number
title: string | number
do(title: string, id: number, status: boolean): void
fn(): void
}
type Todo = ITodo & ITodo2
var todo: Todo = {
id: 1, // Report errors
title: '',
do() {
} // Report errors
fn(){
}
}
And inheritance You can only inherit the content of another interface from one interface
Interface inheritance , If you encounter the same key name but the value does not match , Then an error will be reported when inheriting , Instead of merging into never
Include the name of the method , Even if you want to rewrite it after inheriting , Parameters must also be consistent with those before inheritance
Use type Or use interface The ultimate problem
type and interface It's all about defining types , Constraint variables . And they all support expanding their own fields
In succession / Expand the level of fields
In everyday use ,type It can be used & Operator 2 individual type The merger of , There are “ Conflict ” The field of will Automatically Be merged into never ( In defining type I didn't feel that this field would never)
and inteface What we use is “ Inherit ”, In the course of inheritance , If there is a conflict , Then when defining the interface, you will immediately perceive
At the level of defining types
type You can easily combine basic types , Form a new type , such as
// Define a timestamp field , The timestamp may be a string , It can also be numbers
type TimeStamp = string | number | bigInt
var time: TimeStamp = new Date().getTime()
And the interface type , You must define a complete interface . Limitations for a single field ,type Is slightly better
Speaking of the end , It is estimated that there is no standard to specify what kind of situation should be used to define the type .
If the development content may be a base modular , Many places need to inherit this base Development , That recommendation interface. because This is very interface , And when others inherit the past, they add / You will know immediately when you modify the field , Oh , The original field base Module defines , If I change it like this, it will conflict
and type Types can also be defined , Personally, I think it's more about defining There is no need for external thing , perhaps Things that are not often inherited and modified
such as TS Artistic Gymnastics , The tool classes you see are basically type Defined , because type You can return {}
Can also return to Single field
. At most, when developing tool classes Cross reference , I haven't heard of hold Pick Tool class inherits and adds some functions In this case . type Used to define tool classes , Define a single field , It's very suitable , Defining objects also OK( The interface is not flexible when inheriting ) Each has its own characteristics
So choose type / interface, It still depends on the experience accumulated in business scenarios and code writing . When you write too much , You can see at a glance , This one uses xxx Is the most appropriate
Last
Sum it up
- & Character is used to merge 2 individual / Multiple types of “ intersection ”, When there is conflict in the intersection, it will Automatic conversion to never
- & Yes type and interface Can take effect , For this 2 All definitions can be merged
- extend You can only inherit the content of another interface from one interface
- extend When inheriting an interface, if it is of type “ intersection ” There are conflicts , Then you will be prompted when defining the interface ( Report errors ), Will not automatically convert to never
Since said to type and interface, Finally, I feel that thinking based on the above type combination can smoothly lead to what scenes are suitable for use type Or use it interface
When defining a single field / Define tool classes ( Do type gymnastics ) When type Very suitable
Definition base class / The module needs to provide external functions , Provide the interface / Modules will be inherited by other modules in the past when expanding ,interface Naturally, we should not let it go
边栏推荐
- Word setting directory
- Full Score composition generator: living on code
- 杰理之如若需要大包发送,需要手机端修改 MTU【篇】
- Simple and understandable high-precision addition in C language
- TS类型体操 之 字符串的妙用
- Sélectionnez toutes les lignes avec un symbole dans Word et changez - les en titre
- 超级浏览器是指纹浏览器吗?怎样选择一款好的超级浏览器?
- Google可能在春节后回归中国市场。
- js对象获取属性的方法(.和[]方式)
- Games101 Lesson 7 shading 1 Notes
猜你喜欢
杰理之如若需要大包发送,需要手机端修改 MTU【篇】
When the Jericho development board is powered on, you can open the NRF app with your mobile phone [article]
Relevant introduction of clip image
杰理之AD 系列 MIDI 功能说明【篇】
Oracle column to row -- a field is converted to multiple rows according to the specified separator
Mise en œuvre du langage leecode - C - 15. Somme des trois chiffres - - - - - idées à améliorer
Week6 weekly report
Typescript interface and the use of generics
Twelve rules for naming variables
Path analysis model
随机推荐
Méthode d'obtention des propriétés de l'objet JS (.Et [] méthodes)
【JDBC】快速入门教程
Force buckle day31
杰理之需要修改 gatt 的 profile 定义【篇】
word设置目录
You deserve this high-value open-source third-party Netease cloud music player
Summary of Digital IC design written examination questions (I)
SSM学习
Excel的相关操作
How MySQL merges data
【MySQL学习笔记32】mvcc
Structure summary of SystemVerilog integrable model
Lesson 12 study notes 2022.02.11
杰理之蓝牙设备想要发送数据给手机,需要手机先打开 notify 通道【篇】
The best way to learn SEO: search engine
Jerry's general penetration test - do data transmission with app Communication [article]
leecode-C语言实现-15. 三数之和------思路待改进版
变量的命名规则十二条
Bugku CTF daily question: do you want seeds? Blackmailed
Word setting directory