当前位置:网站首页>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
边栏推荐
猜你喜欢
![最多可以参加的会议数目[贪心 + 优先队列]](/img/f3/e8e939e0393efc404cc159d7d33364.png)
最多可以参加的会议数目[贪心 + 优先队列]

九章云极DataCanvas公司摘获「第五届数字金融创新大赛」最高荣誉!

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

Some important knowledge of MySQL

Ways to improve the utilization of openeuler resources 01: Introduction

Opencv learning notes high dynamic range (HDR) imaging

CSDN syntax description

【STL】vector

Introduction to bit operation

Opencv学习笔记 高动态范围 (HDR) 成像
随机推荐
Gorilla official: sample code for golang to open websocket client
Cloud 组件发展升级
数据孤岛是企业数字化转型遇到的第一道险关
Machine learning notes - explore object detection datasets using streamlit
MRS离线数据分析:通过Flink作业处理OBS数据
干货分享|DevExpress v22.1原版帮助文档下载集合
剑指 Offer II 013. 二维子矩阵的和
openEuler 有奖捉虫活动,来参与一下?
JVM 类加载机制
R language dplyr package mutate_ At function and min_ The rank function calculates the sorting sequence number value and ranking value of the specified data column in the dataframe, and assigns the ra
力扣 2315.统计星号
力扣 459. 重复的子字符串
Force buckle 643 Subarray maximum average I
力扣 1961. 检查字符串是否为数组前缀
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
[sword finger offer] sword finger offer II 012 The sum of left and right subarrays is equal
Visual Studio 插件之CodeMaid自动整理代码
torch. nn. functional. Pad (input, pad, mode= 'constant', value=none) record
搞定带WebKitFormBoundary post登录
Chapter 9 Yunji datacanvas company won the highest honor of the "fifth digital finance innovation competition"!