typescript - 扩展推断的“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
参数接收当前对象加上继承的原型?(最好不要重构为类)
解决方案
你不能用一个简单的变量来做到这一点,你需要一个额外的函数来帮助推理,你需要使用特殊的函数来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()
}
});
推荐阅读
- node.js - 仅在更改时验证 mongoose 字段
- python - Python OpenCV 安装 - 导入 cv2 时出现 DLL 错误
- google-apps-script - 在一个命令中隐藏或显示多列
- neo4j - Neo4j 获得带有评论和喜欢的朋友帖子
- javascript - 在 CommonJS Node 应用程序中导入 ES6 模块?
- javascript - 为 google recapthca v3 获取不同类型的令牌
- python - SAM 无需重建即可运行
- java - 如何将 gmail 中的图片显示到应用程序的导航视图中?
- chromecast - 铬卡斯特服务器酒店
- c# - 在 Apple Silicon 上的 Docker 容器中运行基于 .Net Core 的 Azure 函数