createAbstractFactory()
createAbstractFactory<
K,Products>(families):object
Creates an abstract factory from a record of named family factories.
Each key is a family name, each value is a factory function that produces the product record for that family. All families must produce the same product shape (same keys, same signatures).
The real power is intra-family collaboration: since create returns a
coherent record, products from the same family can reference each other
via closure, guaranteeing compatibility without type gymnastics.
Type Parameters
K: K extends string
Union of family keys
Products: Products extends Record<string, (...args) => unknown>
The record of creator functions each family produces
Parameters
families: Record<K, Factory<Products>>
Record mapping family keys to factory functions
Returns
An abstract factory with create, get, and keys
create(): (key) => Products
Create a product family by key. The factory is called each time, producing a fresh product record.
key:
K
Returns:Products
get(): (key) => Option<Factory<Products>>
Safe lookup for dynamic/runtime keys.
Returns Some(factory) if the key exists, None otherwise.
keys(): () => K[]
Returns all registered family keys.
Returns: K[]
Since
2.4.0
Example
// Products that collaborate: encoder uses the separator from its family
type Codec = {
encode: (parts: string[]) => string;
decode: (raw: string) => string[];
};
const codecs = createAbstractFactory<"csv" | "tsv", Codec>({
csv: () => {
const sep = ",";
return {
encode: (parts) => parts.join(sep),
decode: (raw) => raw.split(sep),
};
},
tsv: () => {
const sep = "\t";
return {
encode: (parts) => parts.join(sep),
decode: (raw) => raw.split(sep),
};
},
});
const csv = codecs.create("csv");
csv.decode(csv.encode(["a", "b"])); // ["a", "b"] — round-trip guaranteed
Factory()<Products>
Factory<
Products> = () =>Products
A Factory is a zero-arg function that produces a product record. Each key in the record is a creator function for one product of the family.
Type Parameters
Products: Products extends Record<string, (...args) => unknown>
The record of creator functions
Returns: Products
Since
2.4.0