当前位置:网站首页>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 :

  1. Use any
    Use any Problems 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 protection

  2. Use 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
原网站

版权声明
本文为[Warmth key]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071801117102.html