JS Built-ins
TypeScriptintermediate

Type Guard β€” validate schema

πŸ“– Usage Example
function isUserSchema(x: unknown): x is { name: string; age: number } {
  return (
    typeof x === 'object' && x !== null &&
    typeof (x as any).name === 'string' &&
    typeof (x as any).age === 'number'
  )
}

Combining property checks into one type guard validates a complete object schema at runtime.

Type Guards: Schema Validation

Challenge: Implement validateUser(x: unknown): x is { name: string; age: number } β€” checking all required fields and their types.

validateUser({ name: 'Alice', age: 30 })    // β†’ true
validateUser({ name: 'Bob' })               // β†’ false (missing age)
validateUser({ name: 'Carol', age: 'old' }) // β†’ false (wrong type)
πŸ’‘ Hints (1)
  • β€’ Check typeof for each property after verifying the key exists.