Superstruct Example

A simple example showing how to use Superstruct in a JSFiddle.

by Brian Birtles

HTML

<script src="https://unpkg.com/superstruct/umd/superstruct.js"></script>

CSS

body {
  margin: 1px;
  padding: 20px;
  white-space: pre;
  font: 12px monospace;
}

.valid {
  background-color: #c2e0c6;
}

.invalid {
  background-color: #fef2c0;
}

JavaScript

const { assert, object, number, string } = window.Superstruct

const User = object({
  id: number(),
  name: string(),
})

const data = {
  id: 'invalid',
  name: 'Jane Smith',
}

try {
  assert(data, User)
  log('valid', data)
} catch (e) {
  const { message, value, type, path, branch } = e
  log('invalid', { message, value, type, path, branch })
}

















function log(type, data) {
  document.body.className = type
  document.body.textContent = JSON.stringify(data, null, 2)
}