@jsonjoy.com/json-type
Version:
High-performance JSON Pointer implementation
57 lines (56 loc) • 2.52 kB
TypeScript
import type { Expr } from '@jsonjoy.com/json-expression';
import type { Type } from './types';
/**
* Discriminator class for automatically identifying distinguishing patterns in
* union types.
*
* This class analyzes types to find discriminatory characteristics that can be
* used to differentiate between variants in a union type at runtime. It can
* autodiscriminate:
*
* - **Constant values** (`ConType`): Exact literal values (strings, numbers, booleans, null)
* - **Primitive types**: `boolean`, `number`, `string` based on JavaScript `typeof`
* - **Structural types**: `object` vs `array` differentiation
* - **Nested discriminators**: Constant values or types found in object properties or array elements
*
* ## Discriminator Specifiers
*
* Specifiers are JSON-encoded arrays `[path, typeSpecifier, value]` that
* uniquely identify discriminators:
*
* **Constant value discriminators** (exact matches):
*
* - `["", "con", "success"]` - Root value must be string "success"
* - `["/type", "con", "user"]` - Property `type` must be string "user"
* - `["/0", "con", 42]` - First array element must be number 42
* - `["", "con", null]` - Root value must be null
*
* **Type-based discriminators** (typeof checks):
*
* - `["", "bool", 0]` - Root value must be boolean (any boolean)
* - `["/age", "num", 0]` - Property `age` must be number (any number)
* - `["/name", "str", 0]` - Property `name` must be string (any string)
* - `["", "obj", 0]` - Root value must be object
* - `["", "arr", 0]` - Root value must be array
*
* **Handling Value Types vs Constants**:
*
* - **Constant values**: When discriminator finds a `ConType`, it creates exact value matches.
* - **Value types**: When discriminator finds primitive types without constants, it matches by `typeof`.
* - **Precedence**: Constant discriminators are preferred over type discriminators for more specific matching.
*
* The discriminator creates JSON Expression conditions that can be evaluated at
* runtime to determine which type variant a value matches in a union type. JSON
* Expression can be compiled to JavaScript for efficient evaluation.
*/
export declare class Discriminator {
readonly path: string;
readonly type: Type;
static findConst(type: Type): Discriminator | undefined;
static find(type: Type): Discriminator;
static createExpression(types: Type[]): Expr;
constructor(path: string, type: Type);
condition(): Expr;
typeSpecifier(): string;
toSpecifier(): string;
}