当前位置:网站首页>TS快速入门-泛型
TS快速入门-泛型
2022-07-07 18:01:00 【温情key】
当我们定义一个变量不确定类型的时候有两种解决方式:
使用any
使用any
定义时存在的问题:虽然知道传入值的类型但是无法获取函数返回值的类型;另外也失去了ts类型保护的优势使用泛型
泛型指在定义函数、接口或类的时候,不预先指定具体的类型,而在使用的时候再指定具体类型的一种特性。
泛型函数
定义一个函数,传入两个参数,第一个参数是任何类型的数据,第二个参数是数量
函数的作用是根据数量产生对应个数的数据,存放在一个数组中
// <>里面传入类型
function getArr<T>(val: T, count: number): Array<T> {
const arr: Array<T> = []; // 也可以这样定义 const arr: T[] = [];
for(let i = 0; i < count; i++) {
arr.push(val)
}
return arr
}
console.log(getArr<string>('温情key', 5)); // [ '温情key', '温情key', '温情key', '温情key', '温情key' ]
// 也可以省略调用时的类型,TS会帮我推断出这个参数的类型
console.log(getArr(true, 3)); // [ true, true, true ]
使用方式类似于函数传参,传什么数据类型,T
就表示什么数据类型,T
也可以换成任意合法字符串。
一个函数也可以定义多个泛型参数
function submit<T, K> (code: T, name: K): T {
console.log(`提交了编号为${
code}的${
typeof code}类型和名称为${
name}的${
typeof name}类型物品`);
return code;
}
submit(123, '兰陵王'); // 提交了编号为123的number类型和名称为兰陵王的string类型物品
submit('SG132', 8848); // 提交了编号为SG132的string类型和名称为8848的number类型物品
泛型接口
在定义接口时, 为接口中的属性或方法定义泛型类型 在使用接口时, 再指定具体的泛型类型
interface Search {
<T, K>(val1: T, val2: K): K
}
const searchHandle: Search = <T, K>(id: T, name: K): K => {
console.log('id' + id + ';' + '名称' + name);
return name
}
searchHandle<number, string>(123, '温情key'); // id123;名称温情key
泛型类
在定义类时, 为类中的属性或方法定义泛型类型 在创建类的实例时, 再指定特定的泛型类型
// 定义泛型类
class Generic<T> {
defaultVal: T;
add: (x: T, y: T) => T;
}
// 创建类实例 - number
const myNum = new Generic<number>();
myNum.defaultVal = 111;
myNum.add = function (x, y) {
console.log(x + y);
return x + y;
}
myNum.add(5, 2); // 7
// 创建类实例 - string
const myStr = new Generic<string>();
myStr.defaultVal = '温情';
myStr.add = function(x, y) {
console.log(myStr.defaultVal + x + y);
return myStr.defaultVal + x + y;
}
myStr.add('k', 'ey'); // 温情key
泛型约束
如果我们直接对一个泛型参数取 length
属性, 会报错, 因为这个泛型根本就不知道它有这个属性
// 没有泛型约束
function fn <T>(x: T): void {
console.log(x.length) // error 类型“T”上不存在属性“length”。
}
我们可以使用泛型约束来实现
interface LengthWise {
length: number;
}
function fn<T extends LengthWise>(x: T): void {
console.log(x.length);
}
/* 需要传入符合约束类型的值,必须包含必须 length 属性: */
// fn(123) // error 类型“number”的参数不能赋给类型“LengthWise”的参数。 因为number没有length属性
fn('温情key'); // 5
边栏推荐
- Some arrangements about oneself
- JVM 类加载机制
- PMP對工作有益嗎?怎麼選擇靠譜平臺讓備考更省心省力!!!
- Redis——基本使用(key、String、List、Set 、Zset 、Hash、Geo、Bitmap、Hyperloglog、事务 )
- R language uses ggplot2 function to visualize the histogram distribution of counting target variables that need to build Poisson regression model, and analyzes the feasibility of building Poisson regr
- 让这个 CRMEB 单商户微信商城系统火起来,太好用了!
- R语言dplyr包select函数、group_by函数、filter函数和do函数获取dataframe中指定因子变量中指定水平中特定数值数据列的值第三大的值
- 多个线程之间如何协同
- Interpretation of transpose convolution theory (input-output size analysis)
- R language ggplot2 visualization: use the ggqqplot function of ggpubr package to visualize the QQ graph (Quantitative quantitative plot)
猜你喜欢
模拟实现string类
Sword finger offer II 013 Sum of two-dimensional submatrix
位运算介绍
vulnhub之school 1
Cloud component development and upgrading
PMP对工作有益吗?怎么选择靠谱平台让备考更省心省力!!!
LeetCode力扣(剑指offer 36-39)36. 二叉搜索树与双向链表37. 序列化二叉树38. 字符串的排列39. 数组中出现次数超过一半的数字
mock.js从对象数组中任选数据返回一个数组
Navicat连接2002 - Can‘t connect to local MySQL server through socket ‘/var/lib/mysql/mysql.sock‘解决
PMP對工作有益嗎?怎麼選擇靠譜平臺讓備考更省心省力!!!
随机推荐
注解。。。
LeetCode_7_5
一锅乱炖,npm、yarn cnpm常用命令合集
力扣 1790. 仅执行一次字符串交换能否使两个字符串相等
RESTAPI 版本控制策略【eolink 翻译】
数据孤岛是企业数字化转型遇到的第一道险关
Make this crmeb single merchant wechat mall system popular, so easy to use!
LeetCode_ 7_ five
PMP practice once a day | don't get lost in the exam -7.7
Some important knowledge of MySQL
mock.js从对象数组中任选数据返回一个数组
Time tools
Cloud 组件发展升级
Automatic classification of defective photovoltaic module cells in electroluminescence images-论文阅读笔记
关于cv2.dnn.readNetFromONNX(path)就报ERROR during processing node with 3 inputs and 1 outputs的解决过程【独家发布】
R language dplyr package mutate_ At function and min_ The rank function calculates the sorting sequence number value and ranking value of the specified data column in the dataframe, and assigns the ra
Semantic SLAM源码解析
Implement secondary index with Gaussian redis
华南X99平台打鸡血教程
R language ggplot2 visualization: use the ggstripchart function of ggpubr package to visualize the dot strip plot, set the position parameter, and configure the separation degree of different grouped