Manual Schema Parser Without Libraries

Validate untrusted input with a small hand-rolled parser that returns a typed result — no schema library needed for flat shapes.

TypescriptSecurity Boundaries

Code

typescriptsnippet
31 lines
type Result<T> = { ok: true; value: T } | { ok: false; errors: string[] };

interface Signup {
  email: string;
  age: number;
}

function parseSignup(input: unknown): Result<Signup> {
  const errors: string[] = [];
  if (typeof input !== 'object' || input === null) {
    return { ok: false, errors: ['payload must be an object'] };
  }
  const raw = input as Record<string, unknown>;

  const email = raw.email;
  if (typeof email !== 'string' || !email.includes('@')) {
    errors.push('email must be a string containing @');
  }

  const age = raw.age;
  if (typeof age !== 'number' || !Number.isInteger(age) || age < 13) {
    errors.push('age must be an integer >= 13');
  }

  if (errors.length > 0) return { ok: false, errors };
  return { ok: true, value: { email: email as string, age: age as number } };
}

console.log(parseSignup({ email: '[email protected]', age: 20 }));
console.log(parseSignup({ email: 'nope', age: 12 }));
console.log(parseSignup('not an object'));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

{ ok: true, value: { email: '[email protected]', age: 20 } }
{
  ok: false,
  errors: [
    'email must be a string containing @',
    'age must be an integer >= 13'
  ]
}
{ ok: false, errors: [ 'payload must be an object' ] }

What each part contributes

Manual Schema Parser Without Libraries comes down to the function parseSignup.

The result comes back as an object carrying false.

Points of care

  • The guard typeof input !== 'object' || input === null short-circuits the flow with an early return when its condition holds.

Putting it to use

The main signature looks like function parseSignup(input: unknown)

The call returns false.

Core lines

return { ok: true, value: { email: email as string, age: age as number } };
return { ok: false, errors: ['payload must be an object'] };
if (errors.length > 0) return { ok: false, errors };

Interactive Tools for This Topic

FAQ

Does `parseSignup` modify its input?
No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
What does the package manager see?
An empty dependency file. The snippet imports nothing that needs fetching. The file defines `parseSignup` at load time.