This is the 13th day of my participation in Gwen Challenge

First, the generic

Generic definitions:

Generic definition refers to the function, interface or class, not specified in advance specific types, and again when using a feature of the specified type, such as to define a function with a parameter, the future in the calling function, the type of the incoming value uncertainty, it is possible that a string, it is possible that number, then you can use generics to solve the problem

  • Example: write a method without specifying what type of array is passed in and returned. Use a generic type instead
function arrayFunc<T> (length:number,value:T) :Array<T> {
    let arr = []
    for (let index = 0; index < length; index++) {
        arr[index] = value
    }
    return arr
}

let arr:string[] = arrayFunc<string>(3.'Joe')
let arrN:number[] = arrayFunc<number>(3.7667)
console.log(arr);
console.log(arrN);

Copy the code

  • Multiple parameter examples
// 2. Multiple parameters
function arrayFunc2<T.K> (name:T,age:K) :T.K] {
    return [name,age]
}

let arr:[string,number] = arrayFunc2('Joe'.18)

console.log(arr);
Copy the code

Interface generics

interface IcreateFunc{
    <T>(name:string,age:T):string
}

let func:IcreateFunc = function<T> (name:string, age:T) {
    return name +age
}

let res = func('Joe'.18)
console.log(res);

Copy the code

3. Use of interface generics in classes

interface Person<T> {
    name: string
    age: number
    getUserInfo: () = > T
}

class userInstance implements Person<string> {
    name: string
    age: number
    constructor(name: string, age: number) {
        this.name = name
        this.age = age
    }
    getUserInfo = () = > ` name:The ${this.name}Age:The ${this.age}`
}

let person = new userInstance('Joe'.18)
let userStr = person.getUserInfo()
console.log(userStr);
Copy the code

2. Generic classes

A generic class defines a generic type for an attribute or method in the class when it is defined, and then specifies a specific generic type when an instance of the class is created

// 1. Generic classes
class Amount<T>{ public num! : T publictotal(price:T,count:T) {
        return Number(price) * Number(count)
    }
}

// When the argument is a numeric value
let amount1 = new Amount<number>()
amount1.num = 5
let totalPrice1 = amount1.total(10, amount1.num)
console.log(totalPrice1,'totalPrice1');


// When the argument is a string
let amount2 = new Amount<string>()
amount2.num = '6'
let totalPrice2 = amount2.total('10', amount2.num)
console.log(totalPrice2,'totalPrice1');
Copy the code

Generic constraints

A generic constraint is a way to ensure that a generic class uses a type that provides a characteristic method. For example, using the Length attribute or push method directly on a generic parameter will result in an error because the method doesn’t even know it has the property or method.

interface ISchema {
    push: Function
    length: number
}

function setV <T extends ISchema> (data:T, value:any) {
    data.push(value)
    console.log(data);
    console.log(data.length);
}

setV([1.2.3].'4')
Copy the code

Namespaces

Namespaces are mainly used to organize code to avoid naming conflicts and solve the problem of duplicate names. In case of large amounts of code, functions, classes, and interfaces with similar functions can be placed in the namespace to avoid conflicting variable names. Typescirpt’s namespace is created using the namespace keyword to wrap code. If you need to access classes or interfaces inside the namespace externally, you need to add the export keyword to the classes and interfaces

Declare a scope with namespace and export it with export

namespace A {
    export let message:string = 'Hello.'
    export function func() {
        console.log('I am the message in the function${message}`);
    }
    export class person {
        name:string = 'Cathy'
        sayHello() {
            console.log(` name:The ${this.name}Say hello `);        
        }
    }
}

A.func()

let person2 = new A.person()

person2.sayHello()
Copy the code