首页 > 解决方案 > 如何在打字稿的对象文字中键入带有“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

解决方案


在 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

推荐阅读