# Schemas

> Build Types from arktype/schema's object format with type.schema, rootSchema, node and schemaScope.

ArkType's syntax parses to a schema format made of [node kinds](https://arktype.io/docs/internals/nodes#node-kinds), and you can write that format directly. It's useful when you generate types from data, like a converter from another schema language, since there's no string to assemble. A Type built this way validates like any other but infers `unknown`.

Schemas are code-equivalent: `type.schema`, `rootSchema`, `node` and `schemaScope` compile schemas into JavaScript functions and require trusted input. Read untrusted JSON Schemas with [`fromJsonSchema`](https://arktype.io/docs/json-schema/from-json-schema), noting its regex and `allOf` limits.

A root schema is one of:

- a domain name: `"string"`
- a constructor: `Date`
- an array of schemas, for a union: `["string", { unit: 5 }]`
- an object keyed by node kinds: `{ domain: "number", min: 0 }`, `{ unit: 5 }`, `{ morphs: ["string", ...] }`

## type.schema

`type.schema` parses a schema into a Type with ArkType's full API:

```ts
const NonEmpty = type.schema({ domain: "string", minLength: 1 })

NonEmpty.expression // "string >= 1"
// ArkErrors: must be non-empty
NonEmpty("")

// cast it if you know the shape
const Typed = NonEmpty.as<string>()
```

## rootSchema

`rootSchema` is `arktype/schema`'s version of `type.schema`. Its result is typed as a node instead of a Type, so it's what you use without `arktype`:

```ts
import "arktype"
import { rootSchema } from "arktype/schema"

const User = rootSchema({
	domain: "object",
	required: [
		{ key: "name", value: "string" },
		{ key: "age", value: { domain: "number", min: 0 } }
	]
})

// ArkErrors: age must be non-negative
User({ name: "Ada", age: -1 })
```

`import "arktype"` installs the [set algebra](https://arktype.io/docs/internals/sets).

## node

`node` creates a single node of a given kind from its inner value. Unlike a schema, the inner value's children must already be nodes:

```ts
import { node, rootSchema } from "arktype/schema"

const NonEmpty = node("minLength", { rule: 1 })
NonEmpty.expression // ">= 1"

const NumberOrString = node("union", {
	branches: [rootSchema("number"), rootSchema("string")]
})
NumberOrString.expression // "number | string"
```

Use it when you already have nodes, such as when you rebuild part of an existing Type. Otherwise `rootSchema` is simpler.

## schemaScope

`schemaScope` defines schemas that reference each other by name with `$`, the way [`scope`](https://arktype.io/docs/scopes) does for definitions:

```ts
import { schemaScope } from "arktype/schema"

const $ = schemaScope({
	user: {
		domain: "object",
		required: [{ key: "id", value: "$id" }]
	},
	id: { domain: "string", minLength: 1 }
})

const { user } = $.export()

// ArkErrors: id must be non-empty
user({ id: "" })
```
