Skip to content

Commit

Permalink
docs: thunk definitions
Browse files Browse the repository at this point in the history
  • Loading branch information
ssalbdivad committed Jan 3, 2025
1 parent db23c90 commit 12348f0
Show file tree
Hide file tree
Showing 5 changed files with 147 additions and 14 deletions.
10 changes: 10 additions & 0 deletions ark/docs/components/snippets/nestedTypeInScopeError.twoslash.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// @errors: 2322
import { scope } from "arktype"
// ---cut---
const myScope = scope({
id: "string#id",
user: type({
name: "string",
id: "id"
})
})
50 changes: 46 additions & 4 deletions ark/docs/content/docs/scopes/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
title: Scopes
---

import { CodeBlock } from "../../../components/CodeBlock.tsx"

<a id="intro" />

Scopes are the foundation of ArkType, and one of the most powerful features for users wanting full control over configuration and to make their own keywords available fluidly within string definition syntax.
Expand Down Expand Up @@ -337,14 +339,54 @@ const rootModule = type.module({

When users are first learning about Scopes, one of the most common mistakes is to reference an alias in a nested `type` call:

<CodeBlock fromFile="nestedTypeInScopeError" />

This error occurs because although the `id` alias would be resolvable in the current Scope directly, `type` only allows references to builtin keywords. In this case, the `type` wrapper is redundant and the fix is to simply remove it:

```ts
// @noErrors
const myScope = scope({
id: "string#id",
user: type({
user: {
name: "string",
// now resolves correctly
id: "id"
})
}
})
```

However, even if it is _possible_ to define your scope without invoking `type` by composing aliases and tuple expressions, the fluent methods available on `Type` can define complex types that can be cumbersome to express otherwise. In these situations, you can use a **thunk definition** to access the `type` method on the Scope you're currently defining:

```ts
const $ = scope({
id: "string#id",
expandUserGroup: () =>
$.type({
name: "string",
id: "id"
})
.or("id")
.pipe(user =>
typeof user === "string" ? { id: user, name: "Anonymous" } : user
)
.array()
.atLeastLength(2)
})

const types = $.export()

// input is validated and transformed to:
// [{ name: "Magical Crawdad", id: "777" }, { name: "Anonymous", id: "778" }]
const groups = types.expandUserGroup([
{ name: "Magical Crawdad", id: "777" },
"778"
])
```

It's a very common mistake to reference a scoped keyword
Though thunk definitions are really only useful when defining a Scope, they can be used anywhere a `Type` definition is expected:

```ts
// you *can* use them anywhere, but *should* you? (no)
const myInelegantType = type(() =>
type({ inelegantKey: () => type("'inelegant value'") })
)
```
3 changes: 2 additions & 1 deletion ark/docs/lib/writeSnippetsEntrypoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ const snippetIds = [
"clarityAndConcision",
"deepIntrospectability",
"intrinsicOptimization",
"unparalleledDx"
"unparalleledDx",
"nestedTypeInScopeError"
] as const

export type SnippetId = (typeof snippetIds)[number]
Expand Down
8 changes: 0 additions & 8 deletions ark/repo/scratch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,3 @@ import { ark, type } from "arktype"
flatMorph(ark.internal.resolutions, (k, v) => [k, v])

console.log(Object.keys(ark.internal.resolutions))

const myScope = type.scope({
id: "string#id",
user: type({
// ParseError: 'id' is not resolvable
id: "id"
})
})
90 changes: 89 additions & 1 deletion ark/type/__tests__/thunk.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { attest, contextualize } from "@ark/attest"
import { writeUnresolvableMessage } from "@ark/schema"
import { scope, type } from "arktype"
import type { Brand } from "@ark/util"
import { scope, type, type Scope } from "arktype"
import { writeBadDefinitionTypeMessage } from "arktype/internal/parser/definition.ts"
import type { Out } from "../attributes.ts"

contextualize(() => {
it("in type", () => {
Expand Down Expand Up @@ -96,4 +98,90 @@ contextualize(() => {
})
attest(() => $.export()).throws(writeUnresolvableMessage("bad"))
})

it("docs example", () => {
const $ = type.scope({
id: "string#id",
expandUserGroup: () =>
$.type({
name: "string",
id: "id"
})
.or("id")
.pipe(user =>
typeof user === "string" ? { id: user, name: "Anonymous" } : user
)
.array()
.atLeastLength(2)
})

attest<
Scope<{
id: Brand<string, "id">
expandUserGroup: ((
In:
| string
| {
name: string
id: string
}
) => Out<{
name: string
id: Brand<string, "id">
}>)[]
}>
>($)

const types = $.export()

const flattenUserMorphs =
types.expandUserGroup.internal.firstReferenceOfKindOrThrow(
"morph"
).serializedMorphs

attest($.json).snap({
id: { domain: "string" },
expandUserGroup: {
sequence: {
in: [
"string",
{
required: [
{ key: "id", value: "string" },
{ key: "name", value: "string" }
],
domain: "object"
}
],
morphs: flattenUserMorphs
},
proto: "Array",
minLength: 2
}
})

const groups = types.expandUserGroup([
{ name: "Magical Crawdad", id: "777" },
"778"
])

type BrandedId = typeof types.id.t

attest(groups).snap([
{ name: "Magical Crawdad", id: "777" as BrandedId },
{ id: "778" as BrandedId, name: "Anonymous" }
])
})

it("docs inelegant", () => {
// you *can* use them anywhere, but *should* you? (no)
const myInelegantType = type(() =>
type({ inelegantKey: () => type("'inelegant value'") })
)

attest(myInelegantType.t).type.toString.snap()
attest(myInelegantType.expression).snap(
'{ inelegantKey: "inelegant value" }'
)
})
})

0 comments on commit 12348f0

Please sign in to comment.