Typing Method Contexts With ThisType
Type object literal methods with ThisType so this refers to the combined data and methods shape, including inside factory helpers.
Code
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);Output
Captured from a sandboxed run of this snippet in the build pipeline.
point: 3 4How this snippet works
Typing Method Contexts With ThisType reduces to the function makeObject.
The result comes back as an object carrying data.
Applying it
point.moveBy(3, 4) mutates the data fields through this, and the single point: line prints the outcome — 3 4 — proving the method saw both the x/y fields from data and its own methods context.
The call returns data.
Statements that matter
const methods = desc.methods ?? ({} as M);
return { ...data, ...methods } as D & M;
const data = desc.data ?? ({} as D);
Interactive Tools for This Topic
FAQ
- Does `makeObject` modify its input?
- No — a new value is constructed for the result and the arguments are never written to.
- Does the runtime need any help from npm, pip, cargo, or the like?
- No — the package manager has nothing to do here; nothing is declared. The file defines `makeObject` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.