当前位置:网站首页>Introduction to the use of TS generics in functions, interfaces and classes
Introduction to the use of TS generics in functions, interfaces and classes
2022-06-26 06:19:00 【One at the front】
One 、 What are generics ? What's the role
There are two ways to solve this problem when we define a variable uncertainty type :
1、 Use any
Use any Problems in definition : although With Know the type of the incoming value but cannot get the type of the return value of the function ; And also lost ts Advantages of type protection
2、 Use generics
Generics refer to defining functions / Interface / Type , Do not specify specific types in advance , It is a feature that specifies type restrictions when using .
Two 、 Use
1、 Using generics in functions
function echo<T>(arg:T):T{
return arg
}
const result=echo(true)
function swap<T,U>(arg:[T,U]):[U,T]{
return [arg[1],arg[0]]
}
const result2=swap(['string',123])
result2[1].charAt(0)2、 Using generics in classes
Example 1
class Animal<T> {
name:T;
constructor(name: T){
this.name = name;
}
action<T>(say:T) {
console.log(say)
}
}
let cat = new Animal('cat');
cat.action('mimi')
Example 2
class Queue<T>{
private data:T[]=[];
push(item:T){
return this.data.push(item)
}
pop(){
return this.data.shift()
}
}
const queue=new Queue<number>()
queue.push(1)
console.log(queue.pop()?.toFixed())
const queue2=new Queue<string>()
queue2.push('12')
console.log(queue2.pop()?.length)3、 Generics are used in interfaces
interface KeyPair<T,U>{
key:T,
value:U
}
let kp1:KeyPair<number,string>={key:1,value:'string'}
let kp2:KeyPair<string,number>={key:'abc',value:12}
let arrTow:Array<number>=[1,2,4]
4、 Constraint generics
interface IWithLength{
length:number
}
function echoWidthLength<T extends IWithLength>(arg:T):T{
console.log(arg.length)
return arg
}
// In this way, the sub parameter can only be passed with length Attribute
const str=echoWidthLength('str')
const obj=echoWidthLength({length:10,width:10})
const arr=echoWidthLength([1,2,3])边栏推荐
- Underlying principle of MySQL index
- Message queuing - omnidirectional comparison
- Getting to know concurrency problems
- 去哪儿网BI平台建设演进史
- Implement the runnable interface
- Mongodb -- use mongodb to intercept the string content in the field and perform grouping statistics
- Data visualization practice: Experimental Report
- Getting started with Python
- MySQL-09
- How to design a good technical scheme
猜你喜欢

低代码实时数仓构建系统的设计与实践

Redis underlying data structure

Efk upgrade to Clickhouse log storage practice

GoF23—原型模式

Getting started with Python

连接数服务器数据库报:错误号码2003Can‘t connect to MySQL server on ‘服务器地址‘(10061)

【Spark】Spark SQL 字段血缘如何实现
Customer Stories | Netease spring breeze: the "spring breeze" of the fun industry, reaching out to all areas through in-depth interaction

技术能力的思考和总结

Keepalived to achieve high service availability
随机推荐
DPDK——TCP/UDP协议栈服务端实现(二)
COW读写复制机制在Linux,Redis ,文件系统中的应用
Deeply uncover Ali (ant financial) technical interview process with preliminary preparation and learning direction
连接数服务器数据库报:错误号码2003Can‘t connect to MySQL server on ‘服务器地址‘(10061)
事务与消息语义
Thinking skills of technical leaders
消息队列-消息事务管理对比
Evolution history of qunar Bi platform construction
Mongodb——使用Mongodb对字段中字符串内容进行截取,并进行分组统计
Playing RTSP streaming video on Web pages (webrtc)
Logstash——Logstash向Email发送告警邮件
Message queue - message transaction management comparison
稀疏数组sparsearray
Five solutions across domains
消息队列-功能、性能、运维对比
[spark] how to implement spark SQL field blood relationship
Tencent WXG internship experience (has offered), I hope it will help you!
EFK昇級到ClickHouse的日志存儲實戰
Web components series (10) -- realize the basic layout of mycard
How can an enterprise successfully complete cloud migration?