当前位置:网站首页>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
边栏推荐
- 2022如何评估与选择低代码开发平台?
- The project manager's "eight interview questions" is equal to a meeting
- 力扣 643. 子数组最大平均数 I
- MIT科技评论文章:围绕Gato等模型的AGI炒作可能使人们忽视真正重要的问题
- The DBSCAN function of FPC package of R language performs density clustering analysis on data, checks the clustering labels of all samples, and the table function calculates the two-dimensional contin
- Cloud component development and upgrading
- 力扣 1232.缀点成线
- mock. JS returns an array from the optional data in the object array
- BI的边界:BI不适合做什么?主数据、MarTech?该如何扩展?
- Introduction to bit operation
猜你喜欢

LeetCode力扣(剑指offer 36-39)36. 二叉搜索树与双向链表37. 序列化二叉树38. 字符串的排列39. 数组中出现次数超过一半的数字

Openeuler prize catching activities, to participate in?

微信公众号OAuth2.0授权登录并显示用户信息

LeetCode_ 7_ five

Welcome to the markdown editor
让这个 CRMEB 单商户微信商城系统火起来,太好用了!

PMP practice once a day | don't get lost in the exam -7.7

LeetCode_7_5

2022如何评估与选择低代码开发平台?

BI的边界:BI不适合做什么?主数据、MarTech?该如何扩展?
随机推荐
How to buy bank financial products? Do you need a bank card?
Mysql, sqlserver Oracle database connection mode
# 欢迎使用Markdown编辑器
ASP. Net gymnasium integrated member management system source code, free sharing
mock.js从对象数组中任选数据返回一个数组
ASP.NET体育馆综合会员管理系统源码,免费分享
Welcome to the markdown editor
Le PGR est - il utile au travail? Comment choisir une plate - forme fiable pour économiser le cœur et la main - d'œuvre lors de la préparation de l'examen!!!
The DBSCAN function of FPC package of R language performs density clustering analysis on data, checks the clustering labels of all samples, and the table function calculates the two-dimensional contin
gorilla官方:golang开websocket client的示例代码
位运算介绍
Boot 和 Cloud 的版本选型
【Auto.js】自动化脚本
openEuler 有奖捉虫活动,来参与一下?
2022如何评估与选择低代码开发平台?
pom. XML configuration file label: differences between dependencies and dependencymanagement
8 CAS
9 原子操作类之18罗汉增强
Automatic classification of defective photovoltaic module cells in electroluminescence images-论文阅读笔记
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