当前位置:网站首页>TS quick start - Generic
TS quick start - Generic
2022-07-07 20:11:00 【Warmth key】
There are two ways to solve this problem when we define a variable uncertainty type :
Use any
Useany
Problems in definition : Although the type of the incoming value is known, the type of the return value of the function cannot be obtained ; And also lost ts Advantages of type protectionUse Generic
Generics refer to defining functions 、 Interface or class , Do not specify specific types in advance , When used, a specific type of feature is specified .
Generic functions
Define a function , Pass in two parameters , The first parameter is any type of data , The second parameter is quantity
The function is used to generate the corresponding number of data according to the number , In an array
// <> Incoming type inside
function getArr<T>(val: T, count: number): Array<T> {
const arr: Array<T> = []; // It can also be defined as const arr: T[] = [];
for(let i = 0; i < count; i++) {
arr.push(val)
}
return arr
}
console.log(getArr<string>(' Warmth key', 5)); // [ ' Warmth key', ' Warmth key', ' Warmth key', ' Warmth key', ' Warmth key' ]
// You can also omit the type when calling ,TS It will help me infer the type of this parameter
console.log(getArr(true, 3)); // [ true, true, true ]
The usage is similar to function parameter passing , What data type is passed ,T
It means what data type ,T
It can also be replaced with any legal string .
A function can also define multiple generic parameters
function submit<T, K> (code: T, name: K): T {
console.log(` Submitted No ${
code} Of ${
typeof code} The type and name are ${
name} Of ${
typeof name} Type item `);
return code;
}
submit(123, ' The king of Lanling '); // Submitted No 123 Of number The type and name is Lanling King string Type item
submit('SG132', 8848); // Submitted No SG132 Of string The type and name are 8848 Of number Type item
Generic interface
When defining interfaces , Define generic types for properties or methods in an interface When using interfaces , Then specify the specific generic type
interface Search {
<T, K>(val1: T, val2: K): K
}
const searchHandle: Search = <T, K>(id: T, name: K): K => {
console.log('id' + id + ';' + ' name ' + name);
return name
}
searchHandle<number, string>(123, ' Warmth key'); // id123; Name warmth key
Generic classes
When defining a class , Define generic types for properties or methods in a class When creating an instance of a class , Then specify a specific generic type
// Define generic classes
class Generic<T> {
defaultVal: T;
add: (x: T, y: T) => T;
}
// Create class instances - 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
// Create class instances - string
const myStr = new Generic<string>();
myStr.defaultVal = ' Warmth ';
myStr.add = function(x, y) {
console.log(myStr.defaultVal + x + y);
return myStr.defaultVal + x + y;
}
myStr.add('k', 'ey'); // Warmth key
Generic constraint
If we take a generic parameter directly length
attribute , Will report a mistake , Because the generic doesn't know it has this attribute at all
// No generic constraints
function fn <T>(x: T): void {
console.log(x.length) // error type “T” Property does not exist on “length”.
}
We can use generic constraints to implement
interface LengthWise {
length: number;
}
function fn<T extends LengthWise>(x: T): void {
console.log(x.length);
}
/* You need to pass in a value that conforms to the constraint type , Must include length attribute : */
// fn(123) // error type “number” Argument to cannot be assigned to type “LengthWise” Parameters of . because number No, length attribute
fn(' Warmth key'); // 5
边栏推荐
- Gorilla official: sample code for golang to open websocket client
- Openeuler prize catching activities, to participate in?
- 力扣674. 最长连续递增序列
- Cloud component development and upgrading
- 第二十章 使用工作队列管理器(三)
- Force buckle 643 Subarray maximum average I
- Chapter 9 Yunji datacanvas company won the highest honor of the "fifth digital finance innovation competition"!
- openEuler 有奖捉虫活动,来参与一下?
- 力扣599. 两个列表的最小索引总和
- With st7008, the Bluetooth test is completely grasped
猜你喜欢
Introduction to bit operation
Yolov6:yolov6+win10--- train your own dataset
Simulate the implementation of string class
华南X99平台打鸡血教程
Detailed explanation of Flink parallelism and slot
论文解读(ValidUtil)《Rethinking the Setting of Semi-supervised Learning on Graphs》
How to cooperate among multiple threads
Automatic classification of defective photovoltaic module cells in electroluminescence images-論文閱讀筆記
数据孤岛是企业数字化转型遇到的第一道险关
使用高斯Redis实现二级索引
随机推荐
Leetcode force buckle (Sword finger offer 36-39) 36 Binary search tree and bidirectional linked list 37 Serialize binary tree 38 Arrangement of strings 39 Numbers that appear more than half of the tim
Creation of kubernetes mysql8
Equals method
使用高斯Redis实现二级索引
力扣 2319. 判断矩阵是否是一个 X 矩阵
Chapter 20 using work queue manager (3)
Gorilla official: sample code for golang to open websocket client
YoloV6:YoloV6+Win10---训练自己得数据集
Force buckle 599 Minimum index sum of two lists
[philosophy and practice] the way of program design
Data island is the first danger encountered by enterprises in their digital transformation
【mysql篇-基础篇】事务
使用高斯Redis实现二级索引
pom. Brief introduction of XML configuration file label function
CUDA versions are inconsistent, and errors are reported when compiling apex
Openeuler prize catching activities, to participate in?
力扣 643. 子数组最大平均数 I
Kubernetes——kubectl命令行工具用法详解
力扣599. 两个列表的最小索引总和
php 获取图片信息的方法