arktype 2.0.0-rc.14 → 2.0.0-rc.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,16 +9,32 @@ import type { instantiateType } from "./instantiate.ts";
9
9
  /** @ts-ignore cast variance */
10
10
  interface Type<out t = unknown, $ = {}> extends Callable<(data: unknown) => distill.Out<t> | ArkErrors> {
11
11
  [inferred]: t;
12
+ /**
13
+ * The top-level generic parameter accepted by the `Type`.\
14
+ * Potentially includes morphs and subtype constraints not reflected
15
+ * in the types fully-inferred input (via `inferIn`) or output (via `infer` or `inferOut`).
16
+ * @example type A = type.infer<[typeof T.t, '[]']>
17
+ */
12
18
  t: t;
19
+ /**
20
+ * A type representing the output the `Type` will return (after morphs are applied to valid input)
21
+ * @example export type MyType = typeof MyType.infer
22
+ * @example export interface MyType extends Identity<typeof MyType.infer> {}
23
+ */
13
24
  infer: this["inferOut"];
14
25
  inferBrandableIn: distill.brandable.In<t>;
15
26
  inferBrandableOut: distill.brandable.Out<t>;
16
27
  inferIntrospectableOut: distill.introspectable.Out<t>;
17
28
  inferOut: distill.Out<t>;
29
+ /**
30
+ * A type representing the input the `Type` will accept (before morphs are applied)
31
+ * @example export type MyTypeInput = typeof MyType.inferIn
32
+ */
18
33
  inferIn: distill.In<t>;
19
34
  inferredOutIsIntrospectable: t extends InferredMorph<any, infer o> ? [
20
35
  o
21
36
  ] extends [anyOrNever] ? true : o extends To ? true : false : unknown extends t ? boolean : true;
37
+ /** Internal JSON representation of this `Type` */
22
38
  json: Json;
23
39
  toJSON(): Json;
24
40
  meta: ArkAmbient.meta;
@@ -28,24 +44,95 @@ interface Type<out t = unknown, $ = {}> extends Callable<(data: unknown) => dist
28
44
  expression: string;
29
45
  internal: BaseRoot;
30
46
  $: Scope<$>;
47
+ /**
48
+ * Validate data, throwing `type.errors` instance on failure
49
+ * @returns a valid value
50
+ * @example const validData = T.assert(rawData)
51
+ */
31
52
  assert(data: unknown): this["infer"];
53
+ /**
54
+ * Check if data matches the input shape.
55
+ * Doesn't process any morphs, but does check narrows.
56
+ * @example type({ foo: "number" }).allows({ foo: "bar" }) // false
57
+ */
32
58
  allows(data: unknown): data is this["inferIn"];
33
59
  traverse(data: unknown): this["infer"] | ArkErrors;
34
60
  brandable(): this;
35
61
  configure(meta: MetaSchema): this;
36
62
  describe(description: string): this;
63
+ /**
64
+ * Create a copy of this `Type` with updated unknown key behavior
65
+ * - `ignore`: ignore unknown properties (default)
66
+ * - 'reject': disallow objects with unknown properties
67
+ * - 'delete': clone the object and keep only known properties
68
+ */
37
69
  onUndeclaredKey(behavior: UndeclaredKeyBehavior): this;
70
+ /**
71
+ * Create a copy of this `Type` with updated unknown key behavior\
72
+ * The behavior applies to the whole object tree, not just the immediate properties.
73
+ * - `ignore`: ignore unknown properties (default)
74
+ * - 'reject': disallow objects with unknown properties
75
+ * - 'delete': clone the object and keep only known properties
76
+ */
38
77
  onDeepUndeclaredKey(behavior: UndeclaredKeyBehavior): this;
78
+ /**
79
+ * Identical to `assert`, but with a typed input as a convenience for providing a typed value.
80
+ * @example const ConfigT = type({ foo: "string" }); export const config = ConfigT.from({ foo: "bar" })
81
+ */
39
82
  from(literal: this["inferIn"]): this["infer"];
83
+ /**
84
+ * Cast the way this `Type` is inferred (has no effect at runtime).
85
+ * const branded = type(/^a/).as<`a${string}`>() // Type<`a${string}`>
86
+ */
40
87
  as<t = unset>(...args: validateChainedAsArgs<t>): instantiateType<t, $>;
88
+ /**
89
+ * A `Type` representing the deeply-extracted input of the `Type` (before morphs are applied).
90
+ * @example const inputT = T.in
91
+ */
41
92
  get in(): instantiateType<this["inferBrandableIn"], $>;
93
+ /**
94
+ * A `Type` representing the deeply-extracted output of the `Type` (after morphs are applied).\
95
+ * **IMPORTANT**: If your type includes morphs, their output will likely be unknown
96
+ * unless they were defined with an explicit output validator via `.to(outputType)`, `.pipe(morph, outputType)`, etc.
97
+ * @example const outputT = T.out
98
+ */
42
99
  get out(): instantiateType<this["inferIntrospectableOut"], $>;
100
+ /**
101
+ * Intersect another `Type` definition, returning an introspectable `Disjoint` if the result is unsatisfiable.
102
+ * @example const intersection = type({ foo: "number" }).intersect({ bar: "string" }) // Type<{ foo: number; bar: string }>
103
+ * @example const intersection = type({ foo: "number" }).intersect({ foo: "string" }) // Disjoint
104
+ */
43
105
  intersect<const def, r = type.infer<def, $>>(def: type.validate<def, $>): instantiateType<inferIntersection<t, r>, $> | Disjoint;
106
+ /**
107
+ * Intersect another `Type` definition, throwing an error if the result is unsatisfiable.
108
+ * @example const intersection = type({ foo: "number" }).intersect({ bar: "string" }) // Type<{ foo: number; bar: string }>
109
+ */
44
110
  and<const def, r = type.infer<def, $>>(def: type.validate<def, $>): instantiateType<inferIntersection<t, r>, $>;
111
+ /**
112
+ * Union another `Type` definition.\
113
+ * If the types contain morphs, input shapes should be distinct. Otherwise an error will be thrown.
114
+ * @example const union = type({ foo: "number" }).or({ foo: "string" }) // Type<{ foo: number } | { foo: string }>
115
+ * @example const union = type("string.numeric.parse").or("number") // Type<((In: string) => Out<number>) | number>
116
+ */
45
117
  or<const def, r = type.infer<def, $>>(def: type.validate<def, $>): instantiateType<t | r, $>;
118
+ /**
119
+ * Add a custom predicate to this `Type`.
120
+ * @example const nan = type('number').narrow(n => Number.isNaN(n)) // Type<number>
121
+ * @example const foo = type("string").narrow((s): s is `foo${string}` => s.startsWith('foo') || ctx.mustBe('string starting with "foo"')) // Type<"foo${string}">
122
+ * @example const unique = type('string[]').narrow((a, ctx) => new Set(a).size === a.length || ctx.mustBe('array with unique elements'))
123
+ */
46
124
  narrow<narrowed extends this["infer"] = never, r = [narrowed] extends [never] ? t extends InferredMorph<infer i, infer o> ? o extends To ? (In: i) => To<applyConstraintSchema<o[1], "predicate", PredicateFn>> : (In: i) => Out<applyConstraintSchema<o[1], "predicate", PredicateFn>> : applyConstraintSchema<t, "predicate", PredicateFn> : t extends InferredMorph<infer i, infer o> ? o extends To ? (In: i) => To<narrowed> : (In: i) => Out<narrowed> : narrowed>(predicate: PredicateFn<this["infer"]> | PredicateCast<this["infer"], narrowed>): instantiateType<r, $>;
47
125
  satisfying<narrowed extends this["inferIn"] = never, r = [narrowed] extends [never] ? applyConstraintSchema<t, "predicate", PredicateFn> : t extends InferredMorph<any, infer o> ? (In: narrowed) => o : narrowed>(predicate: PredicateFn<this["inferIn"]> | PredicateCast<this["inferIn"], narrowed>): instantiateType<r, $>;
126
+ /**
127
+ * Create a `Type` for array with elements of this `Type`
128
+ * @example const T = type(/^foo/); const array = T.array() // Type<string[]>
129
+ */
48
130
  array(): ArrayType<t[], $>;
131
+ /**
132
+ * Morph this `Type` through a chain of morphs.
133
+ * @example const dedupe = type('string[]').pipe(a => Array.from(new Set(a)))
134
+ * @example type({codes: 'string.numeric[]'}).pipe(obj => obj.codes).to('string.numeric.parse[]')
135
+ */
49
136
  pipe: ChainedPipes<t, $>;
50
137
  equals<const def>(def: type.validate<def, $>): boolean;
51
138
  ifEquals<const def, r = type.infer<def, $>>(def: type.validate<def, $>): instantiateType<r, $> | undefined;
@@ -56,6 +143,14 @@ interface Type<out t = unknown, $ = {}> extends Callable<(data: unknown) => dist
56
143
  exclude<const def, r = type.infer<def, $>>(r: type.validate<def, $>): instantiateType<Exclude<t, r>, $>;
57
144
  distribute<mapOut, reduceOut = mapOut[]>(mapBranch: (branch: Type, i: number, branches: array<Type>) => mapOut, reduceMapped?: (mappedBranches: mapOut[]) => reduceOut): reduceOut;
58
145
  optional<r = applyAttribute<t, Optional>>(): instantiateType<r, $>;
146
+ /**
147
+ * Add a default value for this `Type` when it is used as a property.\
148
+ * Default value should be a valid input value for this `Type, or a function that returns a valid input value.\
149
+ * If the type has a morph, it will be applied to the default value.
150
+ * @example const withDefault = type({ foo: type("string").default("bar") }); withDefault({}) // { foo: "bar" }
151
+ * @example const withFactory = type({ foo: type("number[]").default(() => [1])) }); withFactory({baz: 'a'}) // { foo: [1], baz: 'a' }
152
+ * @example const withMorph = type({ foo: type("string.numeric.parse").default("123") }); withMorph({}) // { foo: 123 }
153
+ */
59
154
  default<const value extends this["inferIn"], r = applyAttribute<t, Default<value>>>(value: DefaultFor<value>): instantiateType<r, $>;
60
155
  /** @deprecated */
61
156
  apply: Function["apply"];
@@ -3,6 +3,10 @@ import type { type } from "../keywords/keywords.ts";
3
3
  import type { BaseType } from "./base.ts";
4
4
  /** @ts-ignore cast variance */
5
5
  interface Type<out t = unknown, $ = {}> extends BaseType<t, $> {
6
+ /**
7
+ * Append extra validation shape on the pipe output
8
+ * @example type({codes: 'string.numeric[]'}).pipe(obj => obj.codes).to('string.numeric.parse[]')
9
+ */
6
10
  to<const def, r = type.infer<def, $>>(def: type.validate<def, $>): Type<inferPipe<t, r>, $>;
7
11
  }
8
12
  export type { Type as MorphType };
@@ -13,23 +13,51 @@ interface Type<out t extends object = object, $ = {}> extends BaseType<t, $> {
13
13
  readonly [k in keyof t]: t[k];
14
14
  }, $>;
15
15
  keyof(): instantiateType<arkKeyOf<t>, $>;
16
+ /**
17
+ * Get the `Type` of a property of this `Type<object>`.
18
+ * @example type({ foo: "string" }).get("foo") // Type<string>
19
+ */
16
20
  get<const k1 extends arkIndexableOf<t>, r = arkGet<t, k1>>(k1: k1 | type.cast<k1>): instantiateType<r, $>;
17
21
  get<const k1 extends arkIndexableOf<t>, const k2 extends arkIndexableOf<arkGet<t, k1>>>(k1: k1 | type.cast<k1>, k2: k2 | type.cast<k2>): instantiateType<arkGet<arkGet<t, k1>, k2>, $> extends infer r ? r : never;
18
22
  get<const k1 extends arkIndexableOf<t>, const k2 extends arkIndexableOf<arkGet<t, k1>>, const k3 extends arkIndexableOf<arkGet<arkGet<t, k1>, k2>>, r = arkGet<arkGet<arkGet<t, k1>, k2>, k3>>(k1: k1 | type.cast<k1>, k2: k2 | type.cast<k2>, k3: k3 | type.cast<k3>): instantiateType<r, $>;
23
+ /**
24
+ * Create a copy of this `Type` with only the specified properties.
25
+ * @example type({ foo: "string", bar: "number" }).pick("foo") // Type<{ foo: string }>
26
+ */
19
27
  pick<const key extends arkKeyOf<t> = never>(...keys: (key | type.cast<key>)[]): Type<{
20
28
  [k in keyof t as Extract<toArkKey<t, k>, key>]: t[k];
21
29
  }, $>;
30
+ /**
31
+ * Create a copy of this `Type` with all properties except the specified ones.
32
+ * @example type({ foo: "string", bar: "number" }).omit("foo") // Type<{ bar: number }>
33
+ */
22
34
  omit<const key extends arkKeyOf<t> = never>(...keys: (key | type.cast<key>)[]): Type<{
23
35
  [k in keyof t as Exclude<toArkKey<t, k>, key>]: t[k];
24
36
  }, $>;
37
+ /**
38
+ * Merge another `Type` definition, overriding properties of this `Type` with the duplicate keys.
39
+ * @example type({ a: "1", b: "2" }).merge({ b: "3", c: "4" }) // Type<{ a: 1, b: 3, c: 4 }>
40
+ */
25
41
  merge<const def, r = type.infer<def, $>>(def: type.validate<def, $> & (r extends object ? unknown : ErrorType<"Merged type must be an object", [actual: r]>)): Type<merge<t, r & object>, $>;
42
+ /**
43
+ * Create a copy of this `Type` with all properties required.
44
+ * @example const T = type({ "foo?"": "string" }).required() // Type<{ foo: string }>
45
+ */
26
46
  required(): Type<{
27
47
  [k in keyof t]-?: t[k];
28
48
  }, $>;
49
+ /**
50
+ * Create a copy of this `Type` with all properties optional.
51
+ * @example: const T = type({ foo: "string" }).optional() // Type<{ foo?: string }>
52
+ */
29
53
  partial(): Type<{
30
54
  [k in keyof t]?: t[k];
31
55
  }, $>;
32
56
  map<transformed extends listable<MappedTypeProp>>(flatMapEntry: (entry: typePropOf<t, $>) => transformed): Type<constructMapped<t, transformed>, $>;
57
+ /**
58
+ * List of property info of this `Type<object>`.
59
+ * @example type({ foo: "string = "" }).props // [{ kind: "required", key: "foo", value: Type<string>, default: "" }]
60
+ */
33
61
  props: array<typePropOf<t, $>>;
34
62
  }
35
63
  type typePropOf<o, $> = keyof o extends infer k ? k extends keyof o ? typeProp<o, k, $> : never : never;
package/out/type.d.ts CHANGED
@@ -14,6 +14,11 @@ export interface TypeParser<$ = {}> extends Ark.boundTypeAttachments<$> {
14
14
  <const def, r = Type<type.infer<def, $>, $>>(def: type.validate<def, $>): r;
15
15
  <const params extends ParameterString, const def>(params: validateParameterString<params, $>, def: validateDefinition<def, $, baseGenericConstraints<parseValidGenericParams<params, $>>>): Generic<parseValidGenericParams<params, $>, def, $>;
16
16
  <const zero, const one, const rest extends array, r = Type<type.infer<[zero, one, ...rest], $>, $>>(_0: zero extends IndexZeroOperator ? zero : type.validate<zero, $>, _1: zero extends "keyof" ? type.validate<one, $> : zero extends "instanceof" ? conform<one, Constructor> : zero extends "===" ? conform<one, unknown> : conform<one, IndexOneOperator>, ..._2: zero extends "===" ? rest : zero extends "instanceof" ? conform<rest, readonly Constructor[]> : one extends TupleInfixOperator ? one extends ":" ? [Predicate<distill.In<type.infer<zero, $>>>] : one extends "=>" ? [Morph<distill.Out<type.infer<zero, $>>, unknown>] : one extends "@" ? [MetaSchema] : one extends "=" ? [DefaultFor<distill.In<type.infer<NoInfer<zero>, $>>>] : [type.validate<rest[0], $>] : []): r;
17
+ /**
18
+ * Error class for validation errors
19
+ * Calling type instance returns an instance of this class on failure
20
+ * @example if ( T(data) instanceof type.errors ) { ... }
21
+ */
17
22
  errors: typeof ArkErrors;
18
23
  hkt: typeof Hkt;
19
24
  keywords: typeof keywords;
@@ -24,7 +29,18 @@ export interface TypeParser<$ = {}> extends Ark.boundTypeAttachments<$> {
24
29
  define: DefinitionParser<$>;
25
30
  generic: GenericParser<$>;
26
31
  schema: SchemaParser<$>;
32
+ /**
33
+ * Create a `Type` that is satisfied only by a value strictly equal (`===`) to the argument passed to this function.
34
+ * @example const foo = type.unit('foo') // Type<'foo'>
35
+ * @example const sym: unique symbol = Symbol(); type.unit(sym) // Type<typeof sym>
36
+ */
27
37
  unit: UnitTypeParser<$>;
38
+ /**
39
+ * Create a `Type` that is satisfied only by a value strictly equal (`===`) to one of the arguments passed to this function.
40
+ * @example const enum = type.enumerated('foo', 'bar', obj) // obj is a by-reference object
41
+ * @example const tupleForm = type(['===', 'foo', 'bar', obj])
42
+ * @example const argsForm = type('===', 'foo', 'bar', obj)
43
+ */
28
44
  enumerated: EnumeratedTypeParser<$>;
29
45
  }
30
46
  export declare class InternalTypeParser extends Callable<(...args: unknown[]) => BaseRoot | Generic, TypeParserAttachments> {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "arktype",
3
3
  "description": "TypeScript's 1:1 validator, optimized from editor to runtime",
4
- "version": "2.0.0-rc.14",
4
+ "version": "2.0.0-rc.15",
5
5
  "license": "MIT",
6
6
  "author": {
7
7
  "name": "David Blass",
@@ -34,8 +34,8 @@
34
34
  "out"
35
35
  ],
36
36
  "dependencies": {
37
- "@ark/util": "0.16.0",
38
- "@ark/schema": "0.16.0"
37
+ "@ark/util": "0.17.0",
38
+ "@ark/schema": "0.17.0"
39
39
  },
40
40
  "publishConfig": {
41
41
  "access": "public"