typescript - generics and generic constraints

generic<T>

Sometimes, the parameter type of the function is uncertain, but the parameter type must be the same, or the parameter type and the return value type must be consistent, you can use generic,
generic format - - - put the type in a pair of angle brackets, for example: <T >. The keywords in it are optional, U, K, V, etc. are all available, and T is commonly used to represent the type (type)

When using it, you don’t need to write the incoming generic type, you can automatically deduce the generic type according to the type of the first incoming value, and then use the same generic type later, it will be limited to this type

Sample code:

// 数组重载
function test1(a:number, b:number):Array<number> {
    
    
  return [a, b]
}

function test2(a:string, b:string):Array<string> {
    
    
  return [a, b]
}

// 可以使用泛型,简写
function test3<T>(a:T, b:T):Array<T> {
    
    
  return [a, b]
}

function test4<T,K>(a:T, b:K):Array<T | K> {
    
    
  return [a, b]
}

console.log(test3(1, 2));
console.log(test3('1', '2'));
console.log(test3(true,false));

console.log(test4(true,1));

Print result:

insert image description here

insert image description here

Generic constraints: extends, keyof

Sometimes it is necessary to add a type constraint to the generic type. The limit is under a certain type range, otherwise an error may be reported that the type has no ** operation (extends);
and when obtaining the object attribute value, the key can be constrained to be the key name of the object to be operated (extends + keyof)

Sample code:

function add<T extends number>(a:T, b:T) {
    
    
  return a + b
}
console.log(add(1, 2));


interface len {
    
    
  length: number
}

function test<T extends len>(a:T) {
    
    
  return a.length
}

console.log(test('花花'));
console.log(test(['花花', '何叶']));


function fn<T extends object, K extends keyof T>(a:T, b:K) {
    
    
  return a[b]
}

let obj = {
    
    
  name: '史迪仔',
  age: 100
}
console.log(fn(obj, 'name'));


// 将属性设置为可选
interface Data {
    
    
  name: string,
  age: number,
  sex: string
}

type Options<T extends object> = {
    
    
  [Key in keyof T]?:T[Key]
}

type B = Options<Data>

insert image description here
Print result:

insert image description here

Guess you like

Origin blog.csdn.net/qq_39111074/article/details/132143375