当前位置:网站首页>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
边栏推荐
- How to buy bank financial products? Do you need a bank card?
- 【Auto.js】自动化脚本
- Simulate the implementation of string class
- 力扣 2319. 判断矩阵是否是一个 X 矩阵
- 我的创作纪念日
- JVM class loading mechanism
- RESTAPI 版本控制策略【eolink 翻译】
- LeetCode_ 7_ five
- R language ggplot2 visualization: use the ggdensity function of ggpubr package to visualize the packet density graph, and use stat_ overlay_ normal_ The density function superimposes the positive dist
- sql 常用优化
猜你喜欢

Welcome to the markdown editor

mock. JS returns an array from the optional data in the object array

位运算介绍

九章云极DataCanvas公司获评36氪「最受投资人关注的硬核科技企业」

干货分享|DevExpress v22.1原版帮助文档下载集合

Classification automatique des cellules de modules photovoltaïques par défaut dans les images de lecture électronique - notes de lecture de thèse

openEuler 资源利用率提升之道 01:概论

Cloud component development and upgrading

9 atomic operation class 18 Rohan enhancement

ASP. Net kindergarten chain management system source code
随机推荐
A pot of stew, a collection of common commands of NPM and yarn cnpm
Cloud 组件发展升级
最多可以参加的会议数目[贪心 + 优先队列]
JVM GC垃圾回收简述
Implement secondary index with Gaussian redis
IP 工具类
The project manager's "eight interview questions" is equal to a meeting
mock.js从对象数组中任选数据返回一个数组
谷歌seo外链Backlinks研究工具推荐
gorilla官方:golang开websocket client的示例代码
SQL common optimization
How to buy bank financial products? Do you need a bank card?
Time tools
关于cv2.dnn.readNetFromONNX(path)就报ERROR during processing node with 3 inputs and 1 outputs的解决过程【独家发布】
力扣 2315.统计星号
CSDN syntax description
[RT thread env tool installation]
8 CAS
我的创作纪念日
Classification automatique des cellules de modules photovoltaïques par défaut dans les images de lecture électronique - notes de lecture de thèse