Hand-rolled validation

Type guard functions

A type guard is a function that answers one question about an unknown value. Its return type uses the is keyword, so a true result narrows the value inside later code.

One guard checks one fact, such as non empty text or a positive number. Small guards stay obvious, and obvious checks survive refactors without silent drift. The program asks the guard about a word, an empty string and a number.

function isNonEmptyString(value: unknown): value is string { return typeof value === "string" && value.length > 0; } console.log(isNonEmptyString("Ada"), isNonEmptyString(""), isNonEmptyString(5));

true false false

Parse unknown

Server answers arrive typed as unknown until proven otherwise. A parse function inspects the shape field by field and either returns a clean object or throws a clear message.

Never cast first and hope later. Prove each field with a guard, then build the result from proven parts only. The program parses one good value and catches the message of a bad one.

function isNonEmptyString(value: unknown): value is string { return typeof value === "string" && value.length > 0; } interface User { name: string } function parseUser(value: unknown): User { if (isNonEmptyString(value)) { return { name: value }; } throw new Error("Expected user name text"); } console.log(parseUser("Ada").name); try { parseUser(5); } catch (err: unknown) { console.log((err as Error).message); }

Ada
Expected user name text

Collect errors

Throwing on the first problem hides the rest of the form state. Collecting pushes one message per bad field, so the screen can show all fixes at once.

Return an array of strings and treat empty as valid. The caller keeps control: render the list, highlight fields, or proceed when nothing failed. The program prints how many issues an empty name and a good one produce.

function isNonEmptyString(value: unknown): value is string { return typeof value === "string" && value.length > 0; } function checkUser(name: unknown): string[] { const issues: string[] = []; if (!isNonEmptyString(name)) { issues.push("Name must be non empty text"); } return issues; } console.log(checkUser("").length, checkUser("Ada").length);

1 0

Compose guards

Guards compose like building blocks because each one narrows a little further. Combine two simple checks into one named rule instead of repeating long conditions.

Composition keeps error text in one place and intent in one name. Callers read what a value must be, not how every low level test is spelled. The program asks the composed guard about a name, an empty string and a string of eighty letters.

function isNonEmptyString(value: unknown): value is string { return typeof value === "string" && value.length > 0; } function isName(value: unknown): value is string { return isNonEmptyString(value) && value.length < 80; } console.log(isName("Ada"), isName(""), isName("x".repeat(80)));

true false false

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does the is return type of a guard do?

    Answer

    It narrows the checked value inside the branch where the guard was true

    The value is string annotation tells the compiler what a true answer proves about the argument.

  2. Why inspect an unknown answer field by field?

    Answer

    Because the compiler knows nothing about it, and a cast would only pretend

    A cast silences the compiler without checking anything, while guards prove each field before it is used.

  3. Why collect messages instead of throwing on the first problem?

    Answer

    The reader sees every field to fix at once

    One throw hides the rest of the form state, while an array lets the screen mark every bad field.

  4. What does an empty array from a validator mean?

    Answer

    Nothing failed

    The caller treats an empty list as valid and proceeds, which is the protocol the lesson sets.

  5. What does this program print? function isNonEmptyString(value: unknown): value is string { return typeof value === "string" && value.length > 0; } console.log(isNonEmptyString("Ada"), isNonEmptyString(""));

    Answer

    true false

    The word has letters and the empty string does not, so the two calls differ.

  6. What does this program print? interface User { name: string } function parseUser(value: unknown): User { if (typeof value === "string" && value.length > 0) { return { name: value }; } throw new Error("Expected user name text"); } console.log(parseUser("Ada").name);

    Answer

    Ada

    The string passes the check, and the name field of the parsed user is printed.

  7. What does this program print? function checkUser(name: unknown): string[] { const issues: string[] = []; if (typeof name !== "string" || name.length === 0) { issues.push("Name must be non empty text"); } return issues; } console.log(checkUser(5).length);

    Answer

    1

    A number is not text, so one message is collected and its count is printed.

  8. What does this program print? function isName(value: unknown): value is string { return typeof value === "string" && value.length > 0 && value.length < 80; } console.log(isName("x".repeat(80)), isName("Ada"));

    Answer

    false true

    Eighty letters reach the limit and fail, while the short name passes every part of the rule.

  9. What does the compiler say about this program? function isNonEmptyString(value: unknown): value is string { return typeof value === "string" && value.length > 0; } const value: unknown = 5; if (isNonEmptyString(value)) { console.log(value.toFixed(2)); }

    Answer

    error TS2339: Property 'toFixed' does not exist on type 'string'.

    Inside the branch the guard has narrowed the value to a string, so a number method is refused.

  10. What does the compiler say about this program? function isNonEmptyString(value: unknown): value is string { return typeof value === "string" && value.length > 0; } const value: unknown = 5; console.log(value.toUpperCase());

    Answer

    error TS18046: 'value' is of type 'unknown'.

    Without a guard or a check, an unknown value allows no method at all.

Article author: Arthur Isaev