pikou1995 / pikou1995.github.io

My Github Page
4 stars 1 forks source link

egg extend typescript 的辅助写法 #6

Open pikou1995 opened 4 years ago

pikou1995 commented 4 years ago

egg开发的时候是有egg-ts-helper这个插件辅助的, 在controller, service等里面还是很舒服的. 但是编写extend的时候很别扭.

官方给的例子是使用this paramaters

// app/extend/context.ts
import { Context } from 'egg';

export default {
  isAjax(this: Context) {
    return this.get('X-Requested-With') === 'XMLHttpRequest';
  },
}

这样每个function 都要写很繁琐的写 this, 而且用get的时候编辑器又会报错

// app/extend/context.ts
import { Context } from 'egg';
import Axios from 'axios';

export default {
// 'get' and 'set' accessors cannot declare 'this' parameters.
    get axios(this: Context) {
        return Axios.create();
    }
}

这时候ThisType<Type>就可以来大展身手了!

import { Context } from 'egg'

type ObjectDescriptor<T, E> = T & ThisType<T & E>;

function makeObject<T>(desc: ObjectDescriptor<T, Context>) {
    return desc as T
}

export default makeObject({
    isAjax() {
        // this 就是扩展后的 context
        return this.get('X-Requested-With') === 'XMLHttpRequest';
    },
})

其他 Application, Request 等同理 还有这个功能必须要开启noImplicitThis: true或者strict: true