override
The createOverride() function lets you register changes (default values and/or methods) that will be applied when creating an object.
The typical pattern is:
- create the base object
- call
overrideHandler.apply(self)just before returning it - from another module, register overrides via
setPropertyDefaultValue/setMethod
This tool is heavily used in dataParser to add/alter capabilities without modifying the parser implementation.
WARNING
Overrides are stored in a global store (valid throughout the process): the last override applied to the same property/method wins.
Interactive example
Syntax
typescript
interface OverrideHandler<
GenericInterface extends object
> {
setMethod<
GenericProperty extends keyof GenericInterface
>(
prop: GenericProperty,
theFunction: (
self: GenericInterface,
...args: any[]
) => any
): void;
setPropertyDefaultValue<
GenericProperty extends keyof GenericInterface
>(
prop: GenericProperty,
value: any
): void;
apply(overrideInterface: GenericInterface): GenericInterface;
}
function createOverride<
GenericInterface extends object
>(overrideName: string): OverrideHandler<GenericInterface>;Usage notes
overrideName: choose a unique name (often a namespaced id like@duplojs/utils/...).apply(self): applies overrides and returns a newselfobject (with wrapped methods to receive the correctself).setMethod(...): the function receivesselfas the first parameter, which avoidsthisissues and allows referencing overridden properties.setPropertyDefaultValue(...): sets a value applied at creation (and can overwrite an existing value).
See also
builder- Similar “declare then configure” patternglobalStore- Global per-process storage
