当前位置:网站首页>Typescript -- Section 6 generic
Typescript -- Section 6 generic
2022-06-28 23:48:00 【Run Coder】
/* * Generic * Create reusable components using generics , A component can support multiple types of data * 【 Self understanding 】 Set the type of the parameter to the same form as the function parameter , The type of parameters can be changed at any time according to the wishes of the developer ----< Type variable > * Include : Afferent type and Return type 【 Learning level 】 I learned it once , I feel the knowledge is vague , It still needs practice and more review !! * */
// Example
//identity Functions are called generics
function identity<T>(arg: T): T {
return arg;
}
// There are two ways to define generics 1. Type variable 2. Type inference
let output = identity<string>('string Generic examples ');
// let output = identity("myString"); // type of output will be 'string'
console.log(output)
// Use generic variables
// Array Two forms of writing
function loggingIdentity<T>(arg: Array<T>): Array<T> {
console.log(arg.length); // Array has a .length, so no more error
return arg;
}
loggingIdentity<string>(['1','2','3']);
loggingIdentity<number>([1,2,3]);
function loggingIdentity1<T>(arg: T[]): T[] {
console.log(arg.length); // Array has a .length, so no more error
return arg;
}
// The generic type
// Generic interface
interface GenericIdentityFn {
<T>(arg: T): T;
}
function identity2<T>(arg: T): T {
return arg;
}
// Use an object literal with a call signature to define a generic function
let myIdentity: GenericIdentityFn = identity;
console.log(myIdentity(1))
// Generic classes
//【 remarks 】 Class has two parts : The static part and the instance part . A generic class refers to the type of the instance part , So static properties of a class cannot use this generic type .
class GenericNumber<T> {
zeroValue: T;
add: (x: T, y: T) => T;
}
let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y) {
return x + y; };
// Generic constraint
//【 notes 】 Define an interface to describe constraints , The constrained function is no longer applicable to any type
// Define an inclusion .length Interface to properties , Use this interface and extends Keywords to implement constraints
interface Lengthwise {
length: number;
}
function loggingIdentity2<T extends Lengthwise>(arg: T): T {
console.log(arg.length); // Now we know it has a .length property, so no more error
return arg;
}
loggingIdentity2('string');
// loggingIdentity2(3); // Report errors Argument of type '3' is not assignable to parameter of type 'Lengthwise'.
// Use parameters in generic constraints
function getProperty<T, K extends keyof T>(obj: T, key: K) {
// The official website is not completely written ...
return obj[key];
}
let x = {
a: 100, b: 2, c: 3, d: 4 };
console.log(getProperty(x, "a")); // okay
// getProperty(x, "m"); // error: Argument of type 'm' isn't assignable to 'a' | 'b' | 'c' | 'd'.
// Using class types in generics
class BeeKeeper {
hasMask: boolean;
}
class ZooKeeper {
nametag: string;
}
class Animal {
numLegs: number;
}
class Bee extends Animal {
keeper: BeeKeeper;
}
class Lion extends Animal {
keeper: ZooKeeper;
}
function createInstance<A extends Animal>(c: new () => A): A {
return new c();
}
createInstance(Lion).keeper.nametag; // typechecks!
createInstance(Bee).keeper.hasMask; // typechecks!
The charm of uncertainty and the unknown , Because of the uncertainty , So there is hope , Because of the unknown , So look forward to !
边栏推荐
- ES6模块
- stm32F407-------电容触摸按键
- LinkedIn DataHub --- 经验分享
- Learning fuzzy from SQL injection to bypass the latest safe dog WAF
- 【OpenCV】—线性滤波:方框滤波、均值滤波、高斯滤波
- Rongyun communication solution solves the pain points of enterprise communication
- 融云通信解决方案 破解企业沟通痛点
- 表单校验问题——el-select(初始化页面自动触发校验解决办法)
- 是使用local_setup.bash 还是 setup.bash
- Stm32f407 ------ running lamp and buzzer
猜你喜欢

移动端异构运算技术 - GPU OpenCL 编程(基础篇)

The secondary market is full of bad news. How should the market go next? One article will show you the general trend

Machine learning 6-decision tree

stm32F407-------LCD

Windows10 phpstudy installing redis extension

Mobile heterogeneous computing technology - GPU OpenCL programming (basic)

Stm32f407 ------- IO pin multiplexing mapping

stm32F407-------通用定时器

Online yaml to JSON tool

三个pwn题
随机推荐
stm32F407-------跑马灯、蜂鸣器
Picture 64base transcoding and decoding
stm32F407-------通用定时器
stm32F407-------IO引脚复用映射
Matlab learning notes (6) upsample function and downsample function of MATLAB
ROS2中的行为树 BehaviorTree
[API packet capturing in selenium automation] installation and configuration of browsermobproxy
stm32F407-------电容触摸按键
Online yaml to JSON tool
TypeScript--第五节:类
Yes, use local_ setup. Bash or setup bash
stm32F407-------GPIO输入实验
百度知道爬虫,根据问题id,线索id,评论id获取评论下面的对话
Solve the problem of Chinese parsing by configparser
Save data in Excel: use openpyxl to create multiple tables and set excel row limit
[conception de la machine d'état] Moore, Mealy State Machine, Three - stage, Two - stage, one - stage State Machine Writing Specification
TypeScript -- 第一节:基础类型
Add the premise of ganggan
Implementation of dynamic timer for quartz
Edge extraction based on Halcon learning [2] circles Hdev routine