type.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /*
  2. * Copyright (c) 2018 Mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. */
  6. type Type<T = any> =
  7. | Type.Any | Type.AnyValue | Type.Variable<T> | Type.Value<T>
  8. | Type.Container<T> | Type.Union<T> | Type.OneOf<T>
  9. namespace Type {
  10. export interface Any { kind: 'any', '@type': any }
  11. export interface Variable<T> { kind: 'variable', name: string, type: Type, isConstraint: boolean, '@type': any }
  12. export interface AnyValue { kind: 'any-value', '@type': any }
  13. export interface Value<T> { kind: 'value', namespace: string, name: string, parent?: Value<any>, '@type': T }
  14. export interface Container<T> { kind: 'container', namespace: string, name: string, alias?: string, child: Type, '@type': T }
  15. export interface Union<T> { kind: 'union', types: Type[], '@type': T }
  16. export interface OneOf<T> { kind: 'oneof', type: Value<T>, namespace: string, name: string, values: { [v: string]: boolean | undefined }, '@type': T }
  17. export function Variable<T = any>(name: string, type: Type, isConstraint?: boolean): Variable<T> { return { kind: 'variable', name, type: type, isConstraint } as any; }
  18. export function Value<T>(namespace: string, name: string, parent?: Value<any>): Value<T> { return { kind: 'value', namespace, name, parent } as any; }
  19. export function Container<T = any>(namespace: string, name: string, child: Type, alias?: string): Container<T> { return { kind: 'container', namespace, name, child, alias } as any; }
  20. export function Union<T = any>(types: Type[]): Union<T> { return { kind: 'union', types } as any; }
  21. export function OneOf<T = any>(namespace: string, name: string, type: Value<T>, values: any[]): OneOf<T> {
  22. const vals = Object.create(null);
  23. for (const v of values) vals[v] = true;
  24. return { kind: 'oneof', namespace, name, type, values: vals } as any;
  25. }
  26. export const Any: Any = { kind: 'any' } as any;
  27. export const AnyValue: AnyValue = { kind: 'any-value' } as any;
  28. export const Num = Value<number>('', 'Number');
  29. export const Str = Value<string>('', 'String');
  30. export const Bool = OneOf<boolean>('', 'Bool', Str as any, ['true', 'false']);
  31. export function oneOfValues({ values }: OneOf<any>) { return Object.keys(values).sort(); }
  32. }
  33. export default Type