当前位置:网站首页>Typescript from entry to mastery (XXI) generic types in classes
Typescript from entry to mastery (XXI) generic types in classes
2022-07-29 03:45:00 【Haha, APE】
Generic usage in classes :
We are writing a basic class class In the constructor, you need to pass the names of a group of female characters , And then through getGirlsNmae
Hair method shows the name of the female character
class GirlRole{
constructor(private girls:string[]){
}
getGirlsNmae(index:number):string{
return this.girls[index]
}
}
let girl = new GirlRole([" The daughter of void "," Hicville "," Shadow Hunter "," Xia "])
girl.getGirlsNmae(1)
console.log(girl.getGirlsNmae(1))
// The terminal console prints the results : Hicville
Now better protect the privacy of the role , These roles are numbered , Then our program should be modified like this
class GirlRole{
constructor(private girls:string[]|number[]){
}
getGirlsNmae(index:number):string|number{
return this.girls[index]
}
}
let girl = new GirlRole([" The daughter of void "," Hicville "," Shadow Hunter "," Xia "])
girl.getGirlsNmae(1)
console.log(girl.getGirlsNmae(1))
Obviously, there is no problem with the above code , But not elegant enough , The code looks complex
It can be used at this time Generic
To solve this problem , When we write miscellaneous code everyday Generic
It's often used
class GirlRole<T>{
constructor(private girls:T[]){
}
getGirlsNmae(index:number):T{
return this.girls[index]
}
}
let girl = new GirlRole([" The daughter of void "," Hicville "," Shadow Hunter "," Xia "])
girl.getGirlsNmae(1)
console.log(girl.getGirlsNmae(0))
// The terminal console outputs the results : The daughter of void
We used Generic
, The program also reported no errors , But you will find that we are When instantiating an object , Types are inferred
We said it was Using generics , Just It is best not to use type inference
So we can write like this
let girl = new GirlRole<string>([" The daughter of void "," Hicville "," Shadow Hunter "," Xia "])
Inheritance in generics :
Now the demand has changed again , The return is required to be in an object roleName, That is, the following code should be changed to this way .
getGirlsNmae(index:number):string{
return this.girls[index].roleName
}
The previous code must have reported an error
But at this time, we are also required to do so , This means that the passed value must be of an object type , There's more inside roleName
attribute .
At this time, inheritance is needed , I use interface to realize . Write a Role
The interface of , Every interface should have roleName
attribute . The code is as follows :
interface Role{
roleName:string
}
With the interface, we can use extends
Keyword implements generic inheritance
class GirlRole extends Role{
...
}
This code means that there must be one in a generic roleName
attribute , Because it inherited Role
Interface .
It should be a string
The type is right , So the code should be changed to the following :
interface Role{
roleName:string
}
class GirlRole <T extends Role>{
constructor(private girls:T[]){
}
getGirlsNmae(index:number):string{
return this.girls[index].roleName
}
}
let girlRole = new GirlRole([
{
roleName:" The daughter of void "},
{
roleName:" Hicville "},
{
roleName:" Shadow Hunter "},
{
roleName:" Xia "},
])
girlRole.getGirlsNmae(0)
console.log(girlRole.getGirlsNmae(0))
// Print the results : The daughter of void
Constraints of generics :
Now generics can be of any type , It can be the object 、 character string 、 Boolean 、 Numbers are OK .
But now it is required that this generic type must be string perhaps number type . Let's take the above example , But change the code to its original appearance .
class GirlRole <T>{
constructor(private girls:T[]){
}
getGirlsNmae(index:number):T{
return this.girls[index]
}
}
let girl = new GirlRole([" The daughter of void "," Hicville "," Shadow Hunter "," Xia "])
Then constrain , At this time, you can still use keywords extends
To constrain , Change the code to the following
class GirlRole <T extends string|number>{
constructor(private girls:T[]){
}
getGirlsNmae(index:number):T{
return this.girls[index]
}
}
let girl = new GirlRole([" The daughter of void "," Hicville "," Shadow Hunter "," Xia "])
The above is the basic generic explanation , In practice , The application of generics is more extensive and complex
Learning together , Come on together !!!
边栏推荐
- Environment configuration stepping pit during colab use
- AI platform, AI midrange architecture
- RHCE's at, crontab's basic operations, the Chrony service, symmetric encryption and asymmetric encryption
- How fast does it take to implement a super simple language
- Raft protocol - process demonstration
- MOS tube - rapid recovery application notes (II) [parameters and applications]
- 向日葵资深产品总监技术分享:“国民远控”如何在AD域环境下应用
- Introduction to static routing and dynamic routing protocols OSPF and rip and static routing configuration commands
- Alibaba Font Icon Library Usage and update methods
- 消费行业数字化升级成 “刚需”,weiit 新零售 SaaS 为企业赋能!
猜你喜欢
Instance setup flask service (simple version)
Connection broken by 'readtimc rt-443): read timed out (read timeout=l5)“)‘: /pac
Multi level wavelet CNN for image restoration
从2019 年开始,你一定停止使用了这个营销策略…
RHCE的at,crontab的基本操作,chrony服务和对称加密和非对称加密
Casbin入门
@Configuration (proxybeanmethods = false) what's the use of setting this to false
What you see and think in Microsoft
EMD 经验模态分解
Sleuth+zipkin to track distributed service links
随机推荐
for_each用法示例
Simple understanding of Poe and UPS Technology
1. 头文件-注释-命名空间-标准输入输出流
Some notes on uniapp
Why do programmers so "dislike" the trunk development mode?
AI platform, AI midrange architecture
Deep into C language (1) -- operators and expressions
Excel拼接数据库语句
Target detection, industrial defects, image segmentation -- deep learning data set induction
Sleuth+Zipkin 来进行分布式服务链路的追踪
(newcoder 15079) irrelevant (inclusion exclusion principle)
CUB_200鸟类数据集关键点可视化
Shopify卖家:EDM营销就要搭配SaleSmartly,轻松搞定转化率
for_ Example of each usage
Solve the problem of garbled code when opening the project code in idea
1. Mx6u driver development-2-led driver
How fast does it take to implement a super simple programming language?
(nowcoder22529c) diner (inclusion exclusion principle + permutation and combination)
Cannot paste multiple pictures at once
Use of leak scanning (vulnerability scanning) tool burpsuite or burp Suite (with installation and installation package download of burpsuite+1.7.26)