← 中文资源

简体中文版本

ThisType 标注方法上下文

用 ThisType 标注对象字面量方法:this 指向数据与方法的合并形状,工厂函数返回后仍能获得完整的方法与字段推断。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

point: 3 4

实现说明

逻辑集中在函数 makeObject里。 返回值是携带 data 的对象。

使用要点

  • 演示输出是带标签的(point:),每个操作都会留下自己的一行标注。

常见问题

makeObject 会修改传入的参数吗?

不会——返回值是新建的,入参从不被写入。

运行时需要 npm、pip、cargo 之类帮忙吗?

不需要——包管理器在这里无事可做,没有任何声明。 文件在加载时定义 makeObject。

核心语句

const methods = desc.methods ?? ({} as M);
return { ...data, ...methods } as D & M;
const data = desc.data ?? ({} as D);

代码示例

type ObjectDescriptor<D, M> = {
  data?: D;
  methods?: M & ThisType<D & M>;
};

function makeObject<D, M>(desc: ObjectDescriptor<D, M>): D & M {
  const data = desc.data ?? ({} as D);
  const methods = desc.methods ?? ({} as M);
  return { ...data, ...methods } as D & M;
}

const point = makeObject({
  data: { x: 0, y: 0 },
  methods: {
    moveBy(dx: number, dy: number) {
      // ThisType 让 this 同时看到 data 字段与 methods 方法
      this.x += dx;
      this.y += dy;
    },
  },
});

point.moveBy(3, 4);
console.log('point:', point.x, point.y);