Superstruct Example

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

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: #c2e0c666;
}

.invalid {
  background-color: #fef2c066;
}

JavaScript

const { superstruct, struct } = window.Superstruct

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

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

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








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