Data-plus-method object factories
Define object factories whose methods access properties supplied in a separate data object.
TypeScript · Type Alias
ThisType<T> is a marker for the contextual type of this inside object-literal methods. It is commonly used in factory descriptors so methods can access combined data and method members.
ThisType<T> is a marker used in an object-literal contextual type to define the type of this inside its methods. It does not transform or return a new type; with noImplicitThis enabled, methods can see the combined data and method members.
ThisType<Type>| Name | Type | Description |
|---|---|---|
Type | Type | The type whose members become available through contextual this; in the documented factory pattern it is the combined data and methods type. |
No transformed type; ThisType<T> acts as a contextual marker for the type of this.
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 || {};
const methods = desc.methods || {};
return { ...data, ...methods } as D & M;
}
const obj = makeObject({
data: { x: 0, y: 0 },
methods: {
moveBy(dx: number, dy: number) {
this.x += dx;
this.y += dy;
},
},
});
obj.moveBy(1, 2);This descriptor lets methods use this as the intersection of the data and methods types.
Define object factories whose methods access properties supplied in a separate data object.
Model mixin-like APIs where methods operate on the assembled object.
Infer method declarations while simultaneously using their combined receiver type.
ThisType<T> is a contextual marker for the type of this in object-literal methods. It does not produce a transformed type, and it requires noImplicitThis.
Follow-up: How can a factory expose both data and methods? Use a descriptor whose methods member is intersected with ThisType<D & M>, then return D & M.
In the documented descriptor pattern, methods receive a contextual this type of D & M. That combines the data members with the method members.
Follow-up: Why is the methods property written as both an inference target and a source? It lets TypeScript infer M while using D & M to contextually type method bodies.
ThisType is useful when an object literal contains methods that should access data supplied separately. A factory can use it to model mixin-like object construction without manually annotating every method's this value.
Follow-up: What compiler setting is required? Enable noImplicitThis; otherwise this inside these methods is not checked through this utility.
noImplicitThiscontextual typingintersection typesObjectDescriptormakeObject