typescript - 如何在打字稿的对象文字中键入带有“this”的方法?
问题描述
const log = {
counter: {
a: 1,
b: 2,
c: 3,
},
increment(entry: keyof typeof this.counter){
this.counter[entry]++;
}
};
function incrementLog(entry:keyof typeof log.counter){
log.counter[entry]++;
}
incrementLog('a'); // ok
incrementLog('d'); // error, must be 'a' | 'b' | 'c'
log.increment('a'); // ok
log.increment('d'); // no error
我想强制increment
方法的参数类型为keyof typeof log.counter
,即'a' | 'b' | 'c'
. 我可以在独立功能中实现它,但它在方法中不起作用increment
:'this' is not defined.
我也尝试过log.counter
而不是this.counter
方法定义,但这会创建一个“循环初始化程序”,它也不能按预期工作。
我希望不要手动键入log
或手动键入counter
,因为当我对对象进行更改时,我希望只在一个地方进行更改。
解决方案
在 TypeScript 中编写面向对象的代码时,使用类语法比强制使用普通的对象文字要容易得多:
class Log {
counter = {
a: 1,
b: 2,
c: 3
};
increment(entry: keyof Log['counter']) {
this.counter[entry]++;
}
}
const log = new Log();
function incrementLog(entry:keyof Log['counter']) {
log.counter[entry]++;
}
incrementLog('a'); // ok
incrementLog('d'); // error
log.increment('a'); // ok
log.increment('d'); // error
推荐阅读
- javascript - 滚动位置决定元素高度 - Web 问题
- php - Laravel 与 MySQL 的连接在迁移时有效,但在控制器中无效
- python - 如何根据名称在熊猫中选择一列?
- r - 如何矩阵化列/向量(应用 sum/diff/boolean 之类的函数)?
- sql - Oracle 嵌套连接性能不佳
- python - 无法获取文本提供程序,中止
- python - Python 错误:使用多处理和 Tensorflow 模型时无法腌制 SwigPyObject 对象
- javascript - 切换显示/隐藏 html 内容
- java - 对排序列表中的元素求和,然后将求和值添加到列表中
- reactjs - 如何在我的单元测试中模拟点击反应传单标记?