This is the 10th day of my participation in the More text Challenge. For more details, see more text Challenge
Generic Generics
Generics: a feature that defines a function, interface, or class without specifying a specific type in advance, but instead specifies the type when it is used.
Function echo(arg) {return arg} const result = echo(123); T {return arg} const result = echo(123) function swap<T, U>(tuple: [T, U]): [U, T] {return [tuple[1], tuple[0]]} function total <T, U> (key: T, value: U): [U, T] { return [key, value] } const result = swap(['string', 123])Copy the code
Generics Part 2 – Generics constraints
When you use a generic variable inside a function, you don’t know what type it is, so you can’t arbitrarily manipulate its properties or methods
function echoWithArr<T>(arg: T): T {console.log(arg.length) return arg} // In the example above, the generic type T does not have to contain the property length, we can pass it any type, of course, some do not include the property length, Interface IWithLength {length: number; } function echoWithLength<T extends IWithLength>(arg: T): T { console.log(arg.length) return arg } echoWithLength('str') const result3 = echoWithLength({length: 10}) const result4 = echoWithLength([1, 2, 3])Copy the code
Generics Part 3 – Generics and classes and interfaces
class Queue { private data = []; push(item) { return this.data.push(item) } pop() { return this.data.shift() } } const queue = new Queue() queue.push(1) Queue.push (' STR ') console.log(queue.pop().tofixed ()) console.log(queue.pop().tofixed ()) It allows you to add any type of data to the queue, and of course, it can be any type of data when it gets ejected from the queue. Class Queue<T> {private data = []; class Queue<T> {private data = []; push(item: T) { return this.data.push(item) } pop(): T {return this.data.shift()}} const queue = new queue <number>() value: U; } let kp1: KeyPair<number, string> = { key: 1, value: "str"} let kp2: KeyPair<string, number> = { key: "str", value: 123}Copy the code
People are lazy, do not want to picture, are their own blog content (dry goods), hope to help everyone
Public number: xiao He growth, The Buddha department more text, are their own once stepped on the pit or is learned
Interested partners welcome to pay attention to me, I am: He young life. Everybody progress duck together