-
-
Notifications
You must be signed in to change notification settings - Fork 159
Expand file tree
/
Copy pathllms.txt
More file actions
6214 lines (4574 loc) · 157 KB
/
Copy pathllms.txt
File metadata and controls
6214 lines (4574 loc) · 157 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: Announcing ArkType 2.0
description: 100x faster validation with DX that will blow your mind
---
As of today, `arktype@2.0.0` is generally available and fully stable.
ArkType 2.0 brings types to runtime JS in a way that, until today, has been a pipedream.
Whether you're a first-time TypeScript dev trying to validate a form or a library author introspecting relationships, ArkType offers fundamentally better tools for navigating the perils of JavaScript.
<MainAutoplayDemo />
### Unparalleled DX
Type syntax you already know with safety and completions unlike anything
you've ever seen
<CodeBlock fromFile="unparalleledDx" includesCompletions />
### Faster... everything
100x faster than Zod at runtime with editor performance that will remind you
how autocomplete is supposed to feel
<RuntimeBenchmarksGraph className="mt-2" />
### Clarity and Concision
Definitions are half as long, type errors are twice as readable, and hovers
tell you just what really matters
<CodeBlock fromFile="clarityAndConcision" />
### Better Errors
Deeply customizable messages with great defaults
<CodeBlock fromFile="betterErrors" />
### Deep Introspectability
ArkType uses set theory to understand and expose the relationships between
your types at runtime the way TypeScript does at compile time
<CodeBlock fromFile="deepIntrospectability" />
### Intrinsic Optimization
Every schema is internally normalized and reduced to its purest and fastest
representation
<CodeBlock fromFile="intrinsicOptimization" />
### What next?
ArkType doesn't require a special environment or build step to work- [our intro](/docs/intro/setup) will have you up and running in seconds.
We have [big plans](https://github.com/orgs/arktypeio/projects/4) to ArkType 2.0 even further, but we're even more excited to see what you do with it!
⚡ [Starting coding](/docs/intro/setup)
⭐ [Check out the project on GitHub](https://github.com/arktypeio/arktype)
👋 [Join our Discord to lurk or ask questions](https://arktype.io/discord)
- Follow any of these accounts for updates:
- [@arktype.io](https://bsky.app/profile/arktype.io), [@ssalbdivad.dev](https://bsky.app/profile/ssalbdivad.dev) on BlueSky
- [@arktypeio](https://x.com/arktypeio), [@ssalbdivad](https://x.com/arktypeio) on X/Twitter
- Consider supporting my full-time work on ArkType...
- via [GitHub Sponsors](https://github.com/sponsors/arktypeio)
- by convincing your team to let me optimize your types and fix editor lag (reach out directly to one of the accounts listed or `david@arktype.io`)
---
title: Announcing ArkType 2.1
description: Optimized pattern matching from type syntax
---
As of today, 2.1.0 is generally available 🎉
The biggest feature is `match`, a pattern matching API that allows you to define cases using expressive type syntax. The result is a highly optimized matcher that uses set theory to automatically skip unmatched branches.
We could not be more excited to share this not just as the first syntactic matcher in JS, but as the first ArkType feature to showcase the potential of runtime types to do more than just validation.
Languages with introspectable types offer incredibly powerful features that have always felt out of reach in JS- until now.
```ts
// @noErrors
const toJsonArkType = match({
"string | number | boolean | null": v => v,
bigint: b => `${b}n`,
object: o => {
for (const k in o) {
o[k] = toJsonArkType(o[k])
}
return o
},
default: "assert"
})
const toJsonTsPattern = (value: unknown) =>
tsPatternMatch(value)
.with(P.union(P.string, P.number, P.boolean, null), v => v)
.with(P.bigint, v => `${v}n`)
.with({}, o => {
for (const k in o) {
o[k] = toJsonTsPattern(o[k])
}
return o
})
.otherwise(() => {
throw new Error("value is not valid JSON")
})
// "foo" (9 nanoseconds)
toJsonArkType("foo")
// "foo" (765 nanoseconds)
toJsonTsPattern("foo")
// "5n" (33 nanoseconds)
toJsonArkType(5n)
// "5n" (924 nanoseconds)
toJsonTsPattern(5n)
// { nestedValue: "5n" } (44 nanoseconds)
toJsonArkType({ nestedValue: 5n })
// { nestedValue: "5n" } (2080 nanoseconds)
toJsonTsPattern({ nestedValue: 5n })
```
We're actually huge fans of [Gabriel Vergnaud](https://github.com/gvergnaud) and [ts-pattern](https://github.com/gvergnaud/ts-pattern), which has a great API and totally reasonable performance. We've referenced it for comparison to showcase the unique expressiveness and optimization runtime types unlock.
Below are the full notes for the 2.1.0 release. We can't wait to hear what you think! 🚀
### `match`
The `match` function provides a powerful way to handle different types of input and return corresponding outputs based on the input type, like a type-safe `switch` statement.
#### Case Record API
The simplest way to define a matcher is with ArkType definition strings as keys with corresponding handlers as values:
```ts
import { match } from "arktype"
const sizeOf = match({
"string | Array": v => v.length,
number: v => v,
bigint: v => v,
default: "assert"
})
// a match definition is complete once a `default` has been specified,
// either as a case or via the .default() method
sizeOf("abc") // 3
sizeOf([1, 2, 3, 4]) // 4
sizeOf(5n) // 5n
// ArkErrors: must be an object, a string, a number or a bigint (was boolean)
sizeOf(true)
```
In this example, `sizeOf` is a matcher that takes a string, array, number, or bigint as input. It returns the length of strings and arrays, and the value of numbers and bigints.
`default` accepts one of 4 values:
- `"assert"`: accept `unknown`, throw if none of the cases match
- `"never"`: accept an input based on inferred cases, throw if none match
- `"reject"`: accept `unknown`, return `ArkErrors` if none of the cases match
- `(data: In) => unknown`: handle data not matching other cases directly
Cases will be checked in the order they are specified, either as object literal keys or via chained methods.
#### Fluent API
The `match` function also provides a fluent API. This can be convenient for non-string-embeddable definitions:
```ts
// the Case Record and Fluent APIs can be easily combined
const sizeOf = match({
string: v => v.length,
number: v => v,
bigint: v => v
})
// match any object with a numeric length property and extract it
.case({ length: "number" }, o => o.length)
// return 0 for all other data
.default(() => 0)
sizeOf("abc") // 3
sizeOf({ name: "David", length: 5 }) // 5
sizeOf(null) // 0
```
#### Narrowing input with `in`, property matching with `at`
```ts
// @errors: 2345
type Data =
| {
id: 1
oneValue: number
}
| {
id: 2
twoValue: string
}
const discriminateValue = match
// .in allows you to specify the input TypeScript allows for your matcher
.in<Data>()
// .at allows you to specify a key at which your input will be matched
.at("id")
.match({
1: o => `${o.oneValue}!`,
2: o => o.twoValue.length,
default: "assert"
})
discriminateValue({ id: 1, oneValue: 1 }) // "1!"
discriminateValue({ id: 2, twoValue: "two" }) // 3
discriminateValue({ oneValue: 3 })
```
Special thanks to [@thetayloredman](https://github.com/thetayloredman) who did a mind-blowingly good job helping us iterate toward the current type-level pattern-matching implementation🙇
### Built-in keywords can now be globally configured
This can be very helpful for customizing error messages without needing to create your own aliases or wrappers.
```ts title="config.ts"
import { configure } from "arktype/config"
configure({
keywords: {
string: "shorthand description",
"string.email": {
actual: () => "definitely fake"
}
}
})
```
```ts title="app.ts"
import "./config.ts"
import { type } from "arktype"
const User = type({
name: "string",
email: "string.email"
})
const out = User({
// ArkErrors: name must be shorthand description (was a number)
name: 5,
// ArkErrors: email must be an email address (was definitely fake)
email: "449 Canal St"
})
```
The options you can provide here are identical to those used to [configure a Type directly](https://arktype.io/docs/expressions#meta), and can also be [extended at a type-level to include custom metadata](https://arktype.io/docs/configuration#metadata).
### Tuple and args expressions for `.to`
If a morph returns an `ArkErrors` instance, validation will fail with that result instead of it being treated as a value. This is especially useful for using other Types as morphs to validate output or chain transformations.
To make this easier, there's a special `to` operator that can pipe to a parsed definition without having to wrap it in `type` to make it a function.
This was added before 2.0, but now it comes with a corresponding operator (`|>`) so that it can be expressed via a tuple or args like most other expressions:
```ts
const FluentStillWorks = type("string.numeric.parse").to("number % 2")
const NowSoDoesTuple = type({
someKey: ["string.numeric.parse", "|>", "number % 2"]
})
const AndSpreadArgs = type("string.numeric.parse", "|>", "number % 2")
```
### Error configurations now accept a string directly
```ts
const CustomOne = type("1", "@", {
// previously only a function returning a string was allowed here
message: "Yikes."
})
// ArkErrors: Yikes.
CustomOne(2)
```
Keep in mind, [as mentioned in the docs](https://arktype.io/docs/configuration#errors), error configs like `message` can clobber more granular config options like `expected` and `actual` and cannot be included in composite errors e.g. for a union.
Though generally, returning a string based on context is the best option, in situations where you always want the same static message, it's now easier to get that!
### Type.toString() now wraps its syntactic representation in `Type<..>`
Previously, `Type.toString()` just returned `Type.expression`. However, in contexts where the source of a message isn't always a `Type`, it could be confusing:
```ts
// < 2.1.0: "(was string)"
// >= 2.1.0: "(was Type<string>)"
console.log(`(was ${type.string})`)
```
Hopefully if you interpolate a Type, you'll be less confused by the result from now on!
### Improve how Type instances are inferred when wrapped in external generics
Previously, we used `NoInfer` in some Type method returns. After migrating those to inlined conditionals, we get the same benefit and external inference for cases like this is more reliable:
```ts
// @noErrors
function fn<
T extends {
schema: StandardSchemaV1
}
>(_: T) {
return {} as StandardSchemaV1.InferOutput<T["schema"]>
}
// was inferred as unknown (now correctly { name: string })
const arkRes = fn({
schema: type({
name: "string"
})
})
```
### Fix an issue causing some discriminated unions to incorrectly reject default cases
```ts
const Discriminated = type({
id: "0",
k1: "number"
})
.or({ id: "1", k1: "number" })
.or({
name: "string"
})
// previously, this was rejected as requiring a "k1" key
// will now hit the case discriminated for id: 1,
// but still correctly be allowed via the { name: string } branch
Discriminated({ name: "foo", id: 1 })
```
---
title: Announcing ArkType 2.2
description: Type-safe regex, validated functions, and native Standard Schema definitions
---
As of today, 2.2.0 is generally available 🎉
2.2 brings `type.fn` for runtime-validated functions, type-safe regex via `arkregex`, bidirectional JSON Schema with the new `@ark/json-schema` package, and universal schema interop- embed Zod, Valibot, or any Standard Schema validator directly in your definitions.
For the first time, the type safety ArkType brings to data can extend to your entire function boundary- parameters in, return value out, validated and introspectable. Regex literals now carry full type inference including capture groups. And with configurable `toJsonSchema` and `@ark/json-schema`, ArkType speaks JSON Schema in both directions.
```ts
// @noErrors
import { type } from "arktype"
// runtime-validated functions
const len = type.fn("string | unknown[]", ":", "number")(s => s.length)
len("foo") // 3
len([1, 2, 3]) // 3
// type-safe regex with inferred captures
const Birthday = type({
birthday: "x/^(?<month>\\d{2})-(?<day>\\d{2})-(?<year>\\d{4})$/"
})
Birthday.assert({ birthday: "05-21-1993" }).birthday.groups.month // "05"
// embed any Standard Schema validator
const v = { number: () => "number" as const }
const User = type({ name: "string", age: v.number() })
```
Below are the full notes for the 2.2.0 release. We can't wait to hear what you think! 🚀
### `type.fn` - Validated functions
Define functions with runtime-validated parameters and return types, all using the same syntax you already know. The result is a callable with `.expression`, `.params`, and `.returns` for introspection.
```ts
// @errors: 2345
const len = type.fn("string | unknown[]", ":", "number")(s => s.length)
len("foo") // 3
len([1, 2]) // 2
len.expression // "(string | Array) => number"
len(true) // TraversalError: value at [0] must be a string or an object (was boolean)
```
Since the types are defined as values rather than annotations, `type.fn` also works in plain `.js` files- no JSDoc or TypeScript required to get fully typed, validated function signatures.
Supports all the tuple features you'd expect- defaults, optionals, variadics:
```ts
// "string = 'world'" means the second param defaults to "world" if omitted
const greet = type.fn(
"string",
"string = 'world'"
)((greeting, name) => `${greeting}, ${name}!`)
greet("Hello") // "Hello, world!"
greet("Hey", "David") // "Hey, David!"
// "..." spreads a variadic array parameter, just like in tuple definitions
const join = type.fn(
"...",
"string[]",
":",
"string"
)((...parts) => parts.join(","))
join.expression // "(...string[]) => string"
```
### Type-safe regex
ArkType 2.2 integrates [arkregex](/docs/blog/arkregex), a type-safe wrapper for `new RegExp()`. Regex literals in your definitions now carry full type inference:
```ts
const Hex = type("/^[0-9a-fA-F]+$/")
// Type<string>
const Semver = type("/^(\\d+)\\.(\\d+)\\.(\\d+)$/")
// Type<`${number}.${number}.${number}`>
```
#### e(x)ec mode
Prefix a regex literal with `x` to parse capture groups at runtime, fully typed via arkregex:
```ts
const User = type({
birthday: "x/^(?<month>\\d{2})-(?<day>\\d{2})-(?<year>\\d{4})$/"
})
const data = User.assert({ birthday: "05-21-1993" })
// fully type-safe
data.birthday.groups.month // "05"
data.birthday.groups.day // "21"
data.birthday.groups.year // "1993"
```
For the standalone package (no ArkType required), see the full [arkregex announcement](/docs/blog/arkregex).
### `@ark/json-schema` - Bidirectional JSON Schema
The new `@ark/json-schema` package allows you to parse JSON Schema directly into ArkType Types, complementing the existing `toJsonSchema()` method on every Type. Together, they provide full bidirectional conversion.
Special thanks to [@TizzySaurus](https://github.com/TizzySaurus) for the incredible work on this package 🙌
```ts
declare const jsonSchemaToType: (schema: unknown) => unknown
const User = jsonSchemaToType({
type: "object",
properties: {
name: { type: "string" },
age: { type: "integer", minimum: 0 }
},
required: ["name"]
})
// Type<{ name: string; age?: number }>
```
### Configurable `toJsonSchema`
Some ArkType features don't have JSON Schema equivalents. By default, `toJsonSchema()` throws in these cases. The new fallback config lets you handle incompatibilities granularly:
```ts
const T = type({
"[symbol]": "string",
birthday: "Date"
})
const schema = T.toJsonSchema({
fallback: {
date: ctx => ({
...ctx.base,
type: "string",
format: "date-time",
description: ctx.after ? `after ${ctx.after}` : "anytime"
}),
default: ctx => ctx.base
}
})
```
`toJsonSchema()` now also accepts a `target` option and can generate `draft-07` in addition to the default `draft-2020-12`. Cyclic types are fully supported and generate `$ref`-based schemas.
ArkType also implements the [Standard JSON Schema](https://standardschema.dev) interface, so libraries that consume Standard Schema can access JSON Schema directly via the `~standard` property.
Full documentation including the complete table of fallback codes is available in the [configuration docs](/docs/configuration#tojsonschema).
### Standard Schema as definitions
Any [Standard Schema](https://standardschema.dev) compliant validator can now be passed directly to `type`, either at the top level or nested inside a structural definition, and will be fully inferred and validated.
```ts
import { type } from "arktype"
const v = { number: () => "number" as const }
const z = {
string: () => "string" as const,
object: <shape extends Record<string, unknown>>(shape: shape) => shape
}
const ZodAddress = z.object({
street: z.string(),
city: z.string()
})
const User = type({
name: "string",
age: v.number(),
address: ZodAddress
})
```
This makes ArkType a universal composition layer- mix and match validators from any ecosystem in a single definition.
### `select` - Deep reference introspection
The new `select` method lets you query the internal structure of a type. Every Type is built from a tree of nodes (domains, constraints, morphs, etc.), and `select` extracts references by kind and predicate:
```ts
const T = type("1 < number < 10")
// "min" is the node kind for lower bounds, "exclusive" means > (not >=)
const minNodes = T.select("min")
const exclusiveMins = minNodes.filter(node => node.exclusive)
```
These selectors can also be used to [target specific references for configuration](/docs/expressions#meta), avoiding the need to transform the entire type:
```ts
const User = type({ name: "string", age: "number" })
// add the description to all domain nodes
const configured = User.configure(
{ description: "a special string" },
"domain"
)
configured.get("name").description // "a special string"
configured.get("age").description // "a special string"
```
### Improved `type.declare`
`type.declare` now supports morph-aware declarations via a `side` context, and optionality can be expressed via property values in addition to keys:
```ts
type Expected = { a: string; b?: number }
const T = type.declare<Expected>().type({
a: "string",
// previously failed with `"b?" is missing`
b: "number?"
})
```
If your type includes morphs like `string.numeric.parse`, you can declare just the input side or the output side. This is useful when your external type represents one half of a transformation:
```ts
type Input = { name: string }
// { side: "in" } means we're declaring only the input shape
const T = type.declare<Input, { side: "in" }>().type({
name: "string.numeric.parse"
})
// (In: Input) => { name: number }
```
When there's a mismatch, you get a clear error showing exactly what went wrong:
```ts
// type.declare<{ a: string }>().type({ a: "1" })
// TypeScript: declared: string; inferred: 1
```
### Serializable `ArkErrors`
`ArkErrors` are now JSON stringifiable, making it easy to send validation errors as API responses or store them in logs. Two new properties provide structured access:
```ts
const NEvenAtLeast2 = type({ n: "number % 2 >= 2" })
const out = NEvenAtLeast2({ n: 1 })
if (out instanceof type.errors) {
out.flatByPath
// { n: [{ code: "divisor", rule: 2, ... }, { code: "min", rule: 2, ... }] }
out.flatProblemsByPath
// { n: ["must be even (was 1)", "must be at least 2 (was 1)"] }
}
```
Unhandled validation errors now throw a `TraversalError` (instead of `AggregateError`) with cleaner multi-error formatting (thanks @LukeAbby).
### N-ary operators
`type.or`, `type.and`, `type.merge`, and `type.pipe` are standalone functions that accept variadic definitions, avoiding the need to chain or compose binary expressions:
```ts
const Union = type.or(type.string, "number", { key: "unknown" })
const Intersection = type.and(
{ foo: "string" },
{ bar: "number" },
{ baz: "string" }
)
const Merged = type.merge(
{ "[string]": "number", foo: "0" },
{ "[string]": "bigint", "foo?": "1n" }
)
const TrimToNonEmpty = type.pipe(
type.string,
s => s.trimStart(),
type.string.atLeastLength(1)
)
```
### String-embeddable `|>` pipe operator
The `to` operator (`|>`) can now be used directly inside string definitions:
```ts
const TrimToNonEmpty = type("string.trim |> string > 0")
// equivalent to
const Equivalent = type("string.trim").to("string > 0")
```
### `type.valueOf`
Create a Type from a TypeScript `enum` or enum-like object:
```ts
enum Color {
Red,
Green,
Blue
}
// Type<Color.Red | Color.Green | Color.Blue>
const ColorType = type.valueOf(Color)
```
### New keywords
Two new built-in string keywords:
```ts
// validates hexadecimal strings (thanks @HoaX7)
const Hex = type("string.hex")
Hex.allows("deadbeef") // true
// validates that a string is a syntactically valid regex pattern
const Pattern = type("string.regex")
Pattern.allows("^[a-z]+$") // true
Pattern.allows("[invalid") // false
```
### `exactOptionalPropertyTypes` config
ArkType now supports a global config for `exactOptionalPropertyTypes`, matching TypeScript's compiler option:
```ts title="config.ts"
import { configure } from "arktype/config"
// since the default in ArkType is `true`, this only has an effect if set to `false`
configure({ exactOptionalPropertyTypes: false })
```
```ts title="app.ts"
import "./config.ts"
import { type } from "arktype"
const MyObj = type({ "key?": "number" })
// now valid (would be an error by default)
MyObj({ key: undefined })
```
### Additional improvements
- **`Type#distribute`**: Map and optionally reduce over union branches e.g. `T.distribute(branch => branch.expression)`. See [Type API docs](/docs/type-api#distribute).
- **ES2020 / Hermes compatibility**: Removed usages of newer prototype methods like `.at()` to support legacy browsers and React Native's Hermes engine
- **In-docs playground**: Try ArkType directly from the docs at [arktype.io/playground](https://arktype.io/playground) with full type checking and formatting
- **Cyclic unions can now discriminate on nested paths**, improving performance and error messages for complex recursive types
- **Faster shallow completions**: Near-instant autocomplete for `type("")`
- **Better JSDoc and go-to-definition** for parsed object keys
- **Improved `.expression` for regex constraints**: Now displays `/^pattern$/` instead of `string /^pattern$/`
- **Generic descriptions** are now included for built-in generics like `Record`, `Pick`, `Omit`, `Partial`, `Required`, `Exclude`, `Extract`, and `Merge`
- **`toJsonSchema()` format annotations**: Built-in string keywords like `string.email`, `string.ip.v4`, `string.ip.v6`, `string.url`, and `string.uuid` now emit proper JSON Schema `format` fields, improving OpenAPI compatibility
- **Duplicate key detection**: Definitions with conflicting keys like `{ foo: "string", foo?: "string" }` now throw a descriptive error at parse time
- **Unsatisfiable index signature intersections** now result in a `ParseError` instead of silently producing an unusable type
- **Fixed predicate errors** after the first not being reported for multi-property constraints
- **Fixed clone crash** when an object has a getter or setter as a non-prototype property
- **Fixed custom `message` callbacks in JIT mode** that previously produced `"$ark.message"` instead of the expected string
- **Fixed morph inference for environments** where global prototypes like `FormData` resolve to `{}` (e.g. `@types/bun`)
- **Fixed metatype extraction from recursive definitions** where `Default` and `Out` were not properly inferred
⚡ [Start coding](/docs/intro/setup)
⭐ [Check out the project on GitHub](https://github.com/arktypeio/arktype)
👋 [Join our Discord to lurk or ask questions](https://arktype.io/discord)
- Follow any of these accounts for updates:
- [@arktype.io](https://bsky.app/profile/arktype.io), [@ssalbdivad.dev](https://bsky.app/profile/ssalbdivad.dev) on BlueSky
- [@arktypeio](https://x.com/arktypeio), [@ssalbdivad](https://x.com/ssalbdivad) on X/Twitter
- Consider supporting my full-time work on ArkType...
- via [GitHub Sponsors](https://github.com/sponsors/arktypeio)
- by convincing your team to let me optimize your types and fix editor lag (reach out directly to one of the accounts listed or `david@arktype.io`)
---
title: Introducing ArkRegex
description: A drop-in replacement for new RegExp() with types
---
Regular expressions are ubiquitous in modern code.
A few characters sprinkled into your JavaScript can validate and parse strings that would require dozens of lines of imperative logic.
However, that concision comes at a cost. Complex expressions can be hard to understand and type safety is a pipe dream- or at least, it was.
**Introducing `arkregex`, a type-safe wrapper of `new RegExp()`.**
<video
autoPlay
loop
controls
playsInline
muted
disablePictureInPicture
src="https://github.com/arktypeio/arktype/releases/download/arkregex%400.0.1/arkregexDemo.webm"
style={{ marginTop: "-1rem" }}
/>
The `regex` function creates a `Regex` instance with types for `.test()`, `.exec()` and more, statically parsed from native JS syntax:
```ts
import { regex } from "arkregex"
const ok = regex("^ok$", "i")
// Regex<"ok" | "oK" | "Ok" | "OK", { flags: "i" }>
const semver = regex("^(\\d*)\\.(\\d*)\\.(\\d*)$")
// Regex<`${bigint}.${bigint}.${bigint}`, { captures: [`${bigint}`, `${bigint}`, `${bigint}`] }>
const email = regex("^(?<name>\\w+)@(?<domain>\\w+\\.\\w+)$")
// Regex<`${string}@${string}.${string}`, { names: { name: string; domain: `${string}.${string}`; }; ...>
```
All you need to get started is `pnpm install arkregex` (or the equivalent for your package manager of choice) 🎉
Performs best with TS 5.9+
### Features
- **Types**: Infers string types for your existing regular expressions, including positional and named captures
- **Parity**: Supports 100% of [features](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions) allowed by `new RegExp()`
- **Safety**: Syntax errors like referencing a group that doesn't exist are now type errors
- **Zero Runtime**: Improves your type safety without impacting your bundle size
### FAQ
#### Why aren't some patterns like `[a-Z]` inferred more precisely?
Constructing string literal types for these sorts of expressions is combinatorial and will explode very quickly if we infer character ranges like this as literal characters.
We've tried to strike a balance between performance and precision while guaranteeing that the inferred types are at worst imprecise and never incorrect.
#### Why doesn't it work with my massive RegExp?
If your expression is especially long or complex, TypeScript won't be able to infer it.
If your types start to slow down or you see the dreaded `Type is excessively deep...`, you can manually type your expression using `regex.as`:
```ts
const complexPattern = regex.as<`pattern-${string}`, { captures: [string] }>(
"very-long-complex-expression-here"
)
```
#### Is it robust?
`arkregex` types are [extensively tested](https://github.com/arktypeio/arktype/tree/main/ark/regex/__tests__/regex.test.ts) and [benchmarked](https://github.com/arktypeio/arktype/tree/main/ark/regex/__tests__/regex.bench.ts) using [attest](https://github.com/arktypeio/arktype/tree/main/ark/attest#readme).
If anything not covered by the other FAQs is not behaving how you'd expect, please don't hesitate to [create an issue](https://github.com/arktypeio/arktype/issues/new).
#### How can I get syntax highlighting for my expressions?
The [ArkType extension](https://marketplace.visualstudio.com/items?itemName=arktypeio.arkdark) can be installed to add syntax highlighting to `regex` calls.
### Useful links
⭐ [Check out the project on GitHub](https://github.com/arktypeio/arktype)
👋 [Join our Discord to lurk or ask questions](https://arktype.io/discord)
- Follow any of these accounts for updates:
- [@arktype.io](https://bsky.app/profile/arktype.io), [@ssalbdivad.dev](https://bsky.app/profile/ssalbdivad.dev) on BlueSky
- [@arktypeio](https://x.com/arktypeio), [@ssalbdivad](https://x.com/arktypeio) on X/Twitter
---
title: Posts
---
<LinkCard
title="Announcing ArkType 2.2"
description="Type-safe regex, validated functions, and native Standard Schema definitions"
href="/docs/blog/2.2"
date="February 10, 2026"
/>
<LinkCard
title="Introducing ArkRegex"
description="A drop-in replacement for new RegExp() with types"
href="/docs/blog/arkregex"
date="October 28, 2025"
/>
<LinkCard
title="Announcing ArkType 2.1"
description="Optimized pattern matching from type syntax"
href="/docs/blog/2.1"
date="February 27, 2025"
/>
<LinkCard
title="Announcing ArkType 2.0"
description="100x faster validation with DX that will blow your mind"
href="/docs/blog/2.0"
date="January 17, 2025"
/>
---
title: Comparisons
---
---
title: Configuration
---
A great out-of-the-box experience is a core goal of ArkType, including safe defaults and helpful messages for complex errors.
However, it's equally important that when you need different behavior, you can easily configure it with the right granularity.
### Levels
<table>
<thead>
<tr>
<th>Level</th>
<th>Applies To</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<tr>
<td>**default**</td>
<td>built-in defaults for all Types</td>
<td></td>
</tr>
<tr>
<td>**global**</td>
<td>all Types parsed after the config is applied</td>
<td>
```ts title="config.ts"
import { configure } from "arktype/config"
// use the "arktype/config" entrypoint
configure({ numberAllowsNaN: true })
```
```ts title="app.ts"
import "./config.ts"
// import your config file before arktype
import { type } from "arktype"
type.number.allows(Number.NaN) // true
```
</td>
</tr>
<tr>
<td>**scope**</td>
<td>all Types parsed in the configured Scope</td>
<td>
```ts
const myScope = scope(
{ User: { age: "number < 100" } },
{
max: {
actual: () => "unacceptably large"
}
}
)
const types = myScope.export()
// ArkErrors: age must be less than 100 (was unacceptably large)
types.User({ name: "Alice", age: 101 })
const parsedAfter = myScope.type({
age: "number <= 100"
})
// ArkErrors: age must be at most 100 (was unacceptably large)
parsedAfter({ age: 101 })
```
</td>
</tr>
<tr>
<td>**type**</td>
<td>all Types shallowly referenced by the configured Type</td>
<td>
```ts
// avoid logging "was xxx" for password
const Password = type("string >= 8").configure({ actual: () => "" })
const User = type({
email: "string.email",
password: Password
})
// ArkErrors: password must be at least length 8
const out = User({
email: "david@arktype.io",
password: "ez123"
})
```
</td>
</tr>
</tbody>
</table>
Some options only apply at specific levels, as reflected in the corresponding input types.
<Callout
type="warn"
title='Use the `"arktype/config"` entrypoint in a separate file for global config!'
>
If you need your config to apply to built-in keywords (important for options
like `jitless`, `numberAllowsNaN`, `dateAllowsInvalid`), you should import and
`configure` from `"arktype/config"` before importing anything from
`"arktype"`.
Otherwise, keywords will have already been parsed by the time your config applies!
</Callout>
### Errors
To allow custom errors to be integrated seamlessly with built-in logic for composite errors (i.e. `union` and `intersection`), ArkType supports a set of composable options:
<table>
<thead>
<tr>
<th>optional</th>
<th>description</th>
<th>example</th>
</tr>
</thead>
<tbody>
<tr>
<td>**description**</td>
<td>
✅ a summary of the constraint that could complete the phrase "must be ___"
🥇 reused by other metadata and should be your first go-to for customizing a message
</td>
<td>
```ts
const Password = type.string.atLeastLength(8).describe("a valid password")
// ArkErrors: must be a valid password
const out = Password("ez123")
```