当前位置:网站首页>TypeScript的泛型和泛型约束
TypeScript的泛型和泛型约束
2022-07-02 05:41:00 【用户体验官大龙】
一、泛型
在使用ts封装一个函数时,由于入参是不固定的,必然参数类型也无法固定,这时就要用到泛型来定义参数类型。泛型可以理解为宽泛的类型,通常用于类和函数。
例1. 类中使用泛型
class Person<T>{
private name: T;
constructor(value: T) {
this.name = value;
}
}
const p = new Person<string>('Dalon')例2. 函数中使用泛型
function identity<T>(data: T): T {
console.log(data)
return data;
}
const id1 = identity<string>('hey boy!');
const id2 = identity<number>(123456);例3. 接口中使用泛型
interface Person<T1=string, T2=number> {
name: T1
age: T2
}
const dalon:Person = {
name: 'dalon',
age: 18
}
const tom:Person<string, string> = {
name: 'Tom',
age: '18'
}例3中的T1和T2泛型添加了默认类型,类似于函数的默认参数。
二、泛型约束
泛型约束即是对泛型的类型进行约束控制,如限制为object类型或指定接口类型。当在函数里使用泛型参数的属性或者方法时,就需要对泛型进行约束。
例1. 通过接口约束
interface Lengthwise {
length: number;
}
function loggingIdentity<T extends Lengthwise>(arg: T): T {
console.log(arg.length); // 如果没有Lengthwise泛型约束,会报错Error: T doesn't have .length
return arg;
}例2. object约束
function getKeys<T extends object>(data:T) :string[] {
const keys:Array<string> = Object.keys(data)
return keys
}上面例2的getKeys方法获取一个对象的所有属性名, 由于Object.keys是object的原型方法,所以要求data也必须是一个object类型。
(完)
参考文献:
边栏推荐
- Huawei Hongmeng OS, is it OK?
- 金融门户相关信息
- brew install * 失败,解决方法
- With an amount of $50billion, amd completed the acquisition of Xilinx
- Résumé de la collection de plug - ins couramment utilisée dans les outils de développement idea
- 7. Eleven state sets of TCP
- MySQL foundation --- query (learn MySQL foundation in 1 day)
- 15 C language advanced dynamic memory management
- h5跳小程序
- How to change the IP address of computer mobile phone simulator
猜你喜欢

如何写出好代码 — 防御式编程指南

Centos8 installation mysql8.0.22 tutorial

Software testing learning - day 4

Huawei Hongmeng OS, is it OK?

A collection of commonly used plug-ins for idea development tools

2022-2-14 learning xiangniuke project - Section 7 account setting

数据的储存

Lingyunguang rushes to the scientific innovation board: the annual accounts receivable reaches 800million. Dachen and Xiaomi are shareholders

Fabric. JS gradient

死磕大屏UI,FineReport开发日记
随机推荐
软件测试 - 概念篇
Foreign trade marketing website system development function case making
Simply encapsulate JS and apply it
Gee: analyze the change of spatial centroid of remote sensing image [centroid acquisition analysis]
Grbl software: basic knowledge of simple explanation
1035 Password
ERP management system development and design existing source code
Fabric. JS three methods of changing pictures (including changing pictures in the group and caching)
Gee series: Unit 1 Introduction to Google Earth engine
简单封装 js并应用
Basic use of form
JVM class loading mechanism
6. Network - Foundation
Fabric. JS free draw rectangle
kmp思想及模板代码
Gee series: unit 9 generate sampling data in GEE [random sampling]
Thunder on the ground! Another domestic 5g chip comes out: surpass Huawei and lead the world in performance?
Database batch insert data
“簡單”的無限魔方
1037 Magic Coupon