当前位置:网站首页>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
边栏推荐
- Solve the problem of incomplete display around LCD display of rk3128 projector
- 论文解读(ValidUtil)《Rethinking the Setting of Semi-supervised Learning on Graphs》
- 机器学习笔记 - 使用Streamlit探索对象检测数据集
- Data island is the first danger encountered by enterprises in their digital transformation
- Vulnhub's funfox2
- 力扣 643. 子数组最大平均数 I
- Force buckle 674 Longest continuous increasing sequence
- How to cooperate among multiple threads
- Opencv学习笔记 高动态范围 (HDR) 成像
- mock.js从对象数组中任选数据返回一个数组
猜你喜欢
Cloud 组件发展升级
Simulate the implementation of string class
Sword finger offer II 013 Sum of two-dimensional submatrix
机器学习笔记 - 使用Streamlit探索对象检测数据集
Automatic classification of defective photovoltaic module cells in electroluminescence images-论文阅读笔记
openEuler 资源利用率提升之道 01:概论
关于cv2.dnn.readNetFromONNX(path)就报ERROR during processing node with 3 inputs and 1 outputs的解决过程【独家发布】
使用高斯Redis实现二级索引
PHP method of obtaining image information
Compiler optimization (4): inductive variables
随机推荐
kubernetes之创建mysql8
【剑指offer】剑指 Offer II 012. 左右两边子数组的和相等
mock.js从对象数组中任选数据返回一个数组
R language ggplot2 visualization: use the ggviolin function of ggpubr package to visualize the violin diagram, set the palette parameter to customize the filling color of violin diagrams at different
Equals method
Semantic SLAM源码解析
SQL common optimization
Force buckle 599 Minimum index sum of two lists
Force buckle 2315 Statistical asterisk
841. 字符串哈希
强化学习-学习笔记8 | Q-learning
【STL】vector
微信公众号OAuth2.0授权登录并显示用户信息
Boot 和 Cloud 的版本选型
Automatic classification of defective photovoltaic module cells in electroluminescence images-论文阅读笔记
sql 常用优化
Force buckle 989 Integer addition in array form
Cloud component development and upgrading
pom. XML configuration file label: differences between dependencies and dependencymanagement
Oracle 存储过程之遍历