当前位置:网站首页>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
UseanyProblems 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
边栏推荐
猜你喜欢

关于cv2.dnn.readNetFromONNX(path)就报ERROR during processing node with 3 inputs and 1 outputs的解决过程【独家发布】

CSDN syntax description

RESTAPI 版本控制策略【eolink 翻译】

有了ST7008, 蓝牙测试完全拿捏住了

Open source heavy ware! Chapter 9 the open source project of ylarn causal learning of Yunji datacanvas company will be released soon!

华南X99平台打鸡血教程

Sword finger offer II 013 Sum of two-dimensional submatrix

MRS离线数据分析:通过Flink作业处理OBS数据

Data island is the first danger encountered by enterprises in their digital transformation

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
随机推荐
[auto.js] automatic script
Interpretation of transpose convolution theory (input-output size analysis)
【mysql篇-基础篇】事务
力扣599. 两个列表的最小索引总和
Oracle 存储过程之遍历
The state cyberspace Office released the measures for data exit security assessment: 100000 information provided overseas needs to be declared
vulnhub之Funfox2
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
【哲思与实战】程序设计之道
模拟实现string类
力扣 1790. 仅执行一次字符串交换能否使两个字符串相等
Force buckle 674 Longest continuous increasing sequence
干货分享|DevExpress v22.1原版帮助文档下载集合
Open source heavy ware! Chapter 9 the open source project of ylarn causal learning of Yunji datacanvas company will be released soon!
openEuler 有奖捉虫活动,来参与一下?
Browse the purpose of point setting
CUDA versions are inconsistent, and errors are reported when compiling apex
Equals method
机器学习笔记 - 使用Streamlit探索对象检测数据集
TS快速入门-泛型