当前位置:网站首页>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
边栏推荐
- The differences and advantages and disadvantages between cookies, seeion and token
- [CF Gym101196-I] Waif Until Dark 网络最大流
- Brief explanation of instagram operation tips in 2022
- 合规、高效,加快药企数字化转型,全新打造药企文档资源中心
- How Navicat imports MySQL scripts
- Memory error during variable parameter overload
- Get/post/put/patch/delete meaning
- OpenJudge NOI 2.1 1661:Bomb Game
- Mise en œuvre du langage leecode - C - 15. Somme des trois chiffres - - - - - idées à améliorer
- C # connect to SQLite database to read content
猜你喜欢
Redis builds clusters
How MySQL merges data
Markdown 中设置图片图注
The way to learn go (I) the basic introduction of go to the first HelloWorld
NiO programming introduction
Google可能在春节后回归中国市场。
Ble of Jerry [chapter]
Detailed explanation | detailed explanation of internal mechanism of industrial robot
If Jerry needs to send a large package, he needs to modify the MTU on the mobile terminal [article]
智能终端设备加密防护的意义和措施
随机推荐
Chrome view page FPS
Select all the lines with a symbol in word and change them to titles
Twelve rules for naming variables
Project GFS data download
Bit operation XOR
学go之路(一)go的基本介绍到第一个helloworld
Ble of Jerry [chapter]
C - Inheritance - hidden method
Méthode d'obtention des propriétés de l'objet JS (.Et [] méthodes)
You deserve this high-value open-source third-party Netease cloud music player
Typescript variable scope
Methods for JS object to obtain attributes (. And [] methods)
杰理之BLE【篇】
Force buckle day31
学go之路(二)基本类型及变量、常量
【JDBC】快速入门教程
OpenJudge NOI 2.1 1661:Bomb Game
杰理之蓝牙设备想要发送数据给手机,需要手机先打开 notify 通道【篇】
Full Score composition generator: living on code
How MySQL merges data