skip to content

Primitive Schemas

The scalar building blocks: strings with Zod 4's top-level format helpers, numbers, literals, enums and z.coerce. Interviewers ask what coercion accepts silently and how z.enum takes a TS enum.

questions

5

In Zod 4, what do z.string(), z.number() and z.literal() accept, and why does z.number() reject the string "42"?

level: juniorimportance: must knowfreq 62%

answer

  1. checks the type, never converts
  2. finite numbers only
  3. one exact value per literal
  4. conversion is opt-in

basics

~10 s

Zod 4's scalar schemas check the runtime type without converting: z.string() takes strings, z.number() finite numbers, z.literal() its exact values. "42" is a string, so z.number() rejects it; conversion is opt-in through z.coerce.

solid answer

~40 s

Zod's primitive schemas are type checks, not converters. `z.string()` accepts any string, including an empty one. `z.number()` accepts any finite number, integer or float, and in Zod 4 rejects `NaN`, `Infinity` and `-Infinity` with an `invalid_type` issue. `z.boolean()`, `z.bigint()` and `z.date()` likewise want a real boolean, a bigint or a valid `Date` instance. `z.literal("tuna")` accepts exactly that value, `z.literal(["asc", "desc"])` accepts any of several, and a miss raises `invalid_value`. So `z.number().parse("42")` throws: the input is a string and Zod does not guess. When the input really is text, such as a query string, a form field or an environment variable, you opt into conversion with `z.coerce.number()`, and for whole numbers you add `.int()` or use `z.int()`.

code

typescript · 10 lines
typescript
import * as z from "zod";

z.string().parse("");                          // "" (an empty string is still a string)
z.number().safeParse(42).success;              // true
z.number().safeParse("42").success;            // false: invalid_type, expected number
z.number().safeParse(NaN).success;             // false
z.number().safeParse(Infinity).success;        // false in Zod 4
z.int().safeParse(1.5).success;                // false
z.literal(["asc", "desc"]).safeParse("ASC").success; // false: invalid_value
z.date().safeParse("2024-05-01").success;      // false: z.date() wants a Date instance

go deeper

for a junior

Recall that each primitive schema checks the runtime type and never converts. Be ready to say what z.number() does with "42", NaN and Infinity.

for a middle

Explain why Zod refuses to guess and name the issue codes: invalid_type for a wrong type, invalid_value for a literal miss. Mention the safe-integer rule for z.int().

for a senior

Show where text enters a service and why only those fields need coercion or a format schema, while JSON bodies keep strict primitives.

for a principal

Frame strict primitives as the default worth keeping: every conversion should be a visible, reviewable choice per field, not blanket leniency.

## What a primitive schema is Zod is a TypeScript library that **parses** a value of unknown shape into a typed value or reports why it cannot. A **primitive schema** (also called a scalar schema) describes one JavaScript value that is not an object or array: a string, a number, a boolean, a bigint, a `Date`, or one exact literal value. The key property of every primitive schema in Zod 4 is that it **checks the runtime type and does not convert it**. If the value already has the right type and passes any extra checks you chained on, parsing returns it unchanged. If it has the wrong type, parsing fails with an issue whose `code` says what went wrong. ## The scalar schemas and what each accepts | Schema | Accepts | Rejects (examples) | Issue code on a type miss | |---|---|---|---| | `z.string()` | any string, including `""` | `42`, `null`, `undefined` | `invalid_type` | | `z.number()` | finite numbers, integers and floats | `"42"`, `NaN`, `Infinity` | `invalid_type` | | `z.int()` | safe integers | `1.5`, `"3"` | `invalid_type` | | `z.boolean()` | `true` and `false` | `"true"`, `1` | `invalid_type` | | `z.bigint()` | bigint values such as `10n` | `10`, `"10"` | `invalid_type` | | `z.date()` | valid `Date` instances | ISO strings, an invalid `Date` | `invalid_type` | | `z.literal(v)` | exactly `v`, or one of an array of values | anything else | `invalid_value` | A few details matter in interviews: - `z.string()` does **not** trim and does **not** reject empty strings. Add `.trim()` and `.min(1)` when blank input must fail. - `z.number()` accepts floats. Use `z.int()` (or `.int()` on a number schema) when only whole numbers make sense; in Zod 4 both accept safe integers only. - `z.date()` wants a `Date` object. The string `"2024-05-01"` fails it, because a string is not a `Date`. - `z.literal()` compares with exact equality, so `"ASC"` does not match `"asc"` and `"asc "` with a trailing space does not match either. ## Why "42" fails z.number() `"42"` is a JavaScript string. `z.number()` asks one question, "is this a finite number?", and the answer is no, so it reports an `invalid_type` issue that expects a number. Zod refuses to guess on purpose. Silent conversion hides bad input: a client that sends `"42"` where the contract says `42` has a bug, and a strict schema surfaces it at the boundary instead of deep inside your code. Conversion is therefore something you choose per field: 1. Use `z.coerce.number()` when the input can only ever be text, such as a query-string parameter, a form field or an environment variable. 2. Keep `z.number()` for JSON bodies, where numbers already arrive as numbers. 3. Add bounds such as `.int()` and `.min(1)` after coercion, because conversion alone accepts surprising inputs. ## Literals A **literal schema** represents one exact value: `z.literal("tuna")`, `z.literal(12)`, `z.literal(2n)` or `z.literal(true)`. Passing an array, as in `z.literal(["asc", "desc"])`, accepts any one of several values. A mismatch produces an `invalid_value` issue that lists the allowed values. Zod 4 dropped `symbol` support for literals, because symbols cannot be compared meaningfully as literal values. Literals suit sentinels and small mixed sets. For a named set of strings, `z.enum()` is usually more convenient, because it also exposes helpers such as `.options`. ## Number edge cases, and what Zod 4 tightened Four number edge cases come up in interviews. Zod 4 changed three of them compared with Zod 3; the `NaN` rule stayed as it was: - **No infinite values.** `Infinity` and `-Infinity` are no longer valid for `z.number()`; they fail with `invalid_type`. - **`NaN` stays rejected.** `NaN` has `typeof "number"` in JavaScript, which is exactly why Zod treats it specially. Use `z.nan()` in the rare case where `NaN` itself is the expected value. - **`.int()` accepts safe integers only**, meaning values between `Number.MIN_SAFE_INTEGER` and `Number.MAX_SAFE_INTEGER`, because integers beyond that range lose precision. - `.safe()` is deprecated and now behaves like `.int()`. ## Practical rules 1. Start strict: a primitive schema should match the type the contract promises. 2. When the source is text, reach for `z.coerce` deliberately and then bound the result. 3. Expect `invalid_type` for a wrong type and `invalid_value` for a literal or enum miss; the lesson on issue formatting covers turning those into messages. 4. Do not rely on `typeof x === "number"` reasoning when you think about `z.number()`: `NaN` and `Infinity` pass `typeof` but fail the schema. The result is predictable parsing: a value either already has the declared type and passes, or it fails with an issue that names the expected type.

  • What does Zod 4's z.number() report when an upstream calculation hands it NaN?
    It fails with an `invalid_type` issue expecting a number, and Zod 4 records that the received value was `NaN`. Because `NaN` is a number to JavaScript's `typeof`, Zod rejects it explicitly. If `NaN` really is the value you expect, `z.nan()` exists for that case.
  • Does Zod 4's z.string() reject a whitespace-only value such as " "?
    No. `z.string()` accepts any string as it stands, including `""` and `" "`. If blank input must fail, chain `.trim()` so the value is trimmed before later checks, then `.min(1)`: `z.string().trim().min(1)`. Order matters, because checks run in the order you chain them.
  • When would you pick z.literal() over z.enum() in Zod 4 for a set of allowed values?
    Both accept a fixed set and both raise `invalid_value` on a miss. `z.enum()` is the usual choice for named strings because it offers `.enum`, `.options`, `.extract()` and `.exclude()`. `z.literal()` also takes numbers, bigints and booleans, so it fits a single sentinel such as `z.literal(true)` or a small set that is not all strings.

  • z.number() turns the string "42" into 42 automatically
  • NaN passes z.number() because typeof NaN is number
  • z.date() accepts an ISO date string like 2024-05-01
  • z.string() rejects an empty string by default
  • Infinity is a valid z.number() value in Zod 4

Assumes Zod 4; z.number() stopped accepting Infinity in 4.0 and .int() now accepts safe integers only.

open as a page

In Zod 4, what does z.coerce.number() do to query-string values such as "42", "" and "abc", and what does it accept silently?

level: middleimportance: must knowfreq 58%

basics

~20 s

z.coerce.number() runs Number(input), then the usual finite-number check. "42" becomes 42 and "abc" fails as NaN, but "" becomes 0 and passes, as do " 7 ", "1e3" and "0x1F", so bounds like .int().min(1) must do the rejecting.

open as a page

In Zod 4, how does z.enum() validate a TypeScript enum compared with a string array, and what replaced z.nativeEnum()?

level: middleimportance: should knowfreq 40%

basics

~20 s

In Zod 4, z.enum() accepts both a string array and an enum-like object, so z.nativeEnum() is deprecated. Either way it checks values, not member names: enum Priority { Low = 1, High = 2 } accepts 1 and 2 but rejects "Low" and the text "1".

open as a page

Why does Zod 4 offer z.email(), z.uuid() and z.iso.datetime() as top-level schemas instead of z.string().email(), and what changed in what they accept?

level: middleimportance: should knowfreq 44%

basics

~20 s

In Zod 4 string formats are ZodString subclasses exposed at the top level, shorter and tree-shakable; z.string().email() still works but is deprecated. z.uuid() now enforces RFC variant bits (z.guid() is looser), and z.iso.datetime() rejects offsets unless configured.

open as a page

Why does a Zod 4 search schema that declares active as z.coerce.boolean() turn the query value active=false into true, and what should replace it?

level: seniorimportance: should knowfreq 48%

basics

~20 s

z.coerce.boolean() calls Boolean(input), and every non-empty string, "false" included, is truthy, so it becomes true. Replace it with z.stringbool(), added in Zod 4.0, which maps listed words such as "false", "0" and "no" to false and rejects unlisted text.

open as a page