首页 > 解决方案 > 扩展推断的“this”

问题描述

假设我有一个基本原型:

const proto = {
  const1: 1,
  const2: 2
}

现在,我在某个地方编写了另一个应该可以访问此基本原型的对象。在第一次尝试时,它失败了。

const consumer = {
  method1(): number {
    return this.const1 //const1 does no exist
  },
  method2() {
    return this.method1()
  }
}

第二次尝试

//consumer is downcast to 'any' since it references itself
const consumer = {
  method1(this: typeof consumer & typeof proto): number {
    return this.const1
  },
  method2() {
    return this.method1()
  }
}

是否有任何技巧或方法可以告诉this参数接收当前对象加上继承的原型?(最好不要重构为类)

标签: typescript

解决方案


你不能用一个简单的变量来做到这一点,你需要一个额外的函数来帮助推理,你需要使用特殊的函数来ThisType<T>告诉编译器this对象字面量中定义的任何类型应该是什么:

const proto = {
    const1: 1,
    const2: 2
}


function extend<TBase, TCurrent>(base: TBase, current: TCurrent & ThisType<TCurrent & TBase>): TCurrent & TBase {
    return Object.assign(current, base);
}
const consumer = extend(proto, {
    method1(): number {
        return this.const1 //works
    },
    method2() {
        return this.method1()
    }
});

推荐阅读