UNPKG

2.21 kBTypeScriptView Raw
1import { DataObject, PrototypeOf } from './common-types';
2import { Model, ModelDefinition } from './model';
3/**
4 * Create (define) a new model class with the given name and definition.
5 *
6 * @remarks
7 *
8 * ```ts
9 * const Product = defineModelClass(Entity, new ModelDefinition('Product'));
10 * ```
11 *
12 * To enable type safety, you should describe properties of your model:
13 *
14 * ```ts
15 * const Product = defineModelClass<
16 * typeof Entity,
17 * {id: number, name: string}
18 * >(Entity, new ModelDefinition('Product'));
19 * ```
20 *
21 * If your model allows arbitrary (free-form) properties, then add `AnyObject`
22 * to the type describing model properties.
23 *
24 * ```ts
25 * const Product = defineModelClass<
26 * typeof Entity,
27 * AnyObject & {id: number},
28 * >(Entity, new ModelDefinition('Product'));
29 * ```
30 *
31 * @param base The base model to extend, typically Model or Entity.
32 * You can also use your own base class, e.g. `User`.
33 * @param definition Definition of the model to create.
34 * @typeParam BaseCtor Constructor type of the base class,
35 * e.g `typeof Model` or `typeof Entity`
36 * @typeParam Props Interface describing model properties,
37 * e.g. `{title: string}` or `AnyObject & {id: number}`.
38 */
39export declare function defineModelClass<BaseCtor extends typeof Model, Props extends object = {}>(base: BaseCtor, definition: ModelDefinition): DynamicModelCtor<BaseCtor, Props>;
40/**
41 * A type describing a model class created via `defineModelClass`.
42 *
43 * Assuming template arguments `BaseCtor` and `Props`, this type describes
44 * a class constructor with the following properties:
45 * - a constructor function accepting `DataObject<Props>` as the only argument,
46 * this argument is optional
47 * - all static fields (properties, methods) from `BaseCtor` are inherited and
48 * available as static fields on the dynamic class
49 * - all prototype fields from `BaseCtor` prototype are inherited and available
50 * as prototype fields on the dynamic class
51 */
52export type DynamicModelCtor<BaseCtor extends typeof Model, Props extends object> = {
53 /** Model constructor accepting partial model data. */
54 new (data?: DataObject<PrototypeOf<BaseCtor> & Props>): PrototypeOf<BaseCtor> & Props;
55} & BaseCtor;