Skip to content

TypeScript

泛型

  1. 可以通过泛型占位类型,再调用函数时确定类型
  2. 给对象使用泛型
  3. 请求封装,给Promise返回类型加上泛型
  4. 泛型约束,访问对象的属性,必须传入已有的key
  5. 给对象的属性使用泛型
ts
function build<T>(a: T, b: T): Array<T> {
  return [a, b];
}

function build<T,U>(a: T, b: U): Array<T | U> {
  return [a, b];
}

build(1, 2);
build('a', 'b');
ts
interface User<T>{
    name:T
}

let a:User<string> = {name:'a'}
ts
const axios = {
    get<T>(url:string):Promise<T> {
        return new Promise<T>((resolve, reject) => {
            resolve(obect)
        })
    }
}

interface User {
    name:string
}

axios.get<User>('/user').then(res => {
    console.log(res.name)
})
ts
const object = {
    name: 'modify',
    age: 18
}

function get<T extends object, K extends keyof T>(obj:T, key:K){
    return obj[key]
}
ts
interface Data {
  name: string;
  age: number;
  sex: string;
}

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

type DataOption = Options<Data>;

By Modify.