title: Easy way to validate the shape of an object in Javascript
body: <p>I’m wondering if there’s a simple way of validating the shape of an object in Javascript.</p>
  
  <p>Right now, I have a function that validates the shape of endpoint objects like this:</p>
  
  <pre><code>function validateEndpointShape(endpoint: any, hasId: boolean): boolean 
  {
  return endpoint
  &amp;&amp; (hasId ? typeof endpoint.id === 'string' : true)
  &amp;&amp; typeof endpoint.name === 'string'
  &amp;&amp; typeof endpoint.description === 'string'
  &amp;&amp; typeof endpoint.url === 'string'
  &amp;&amp; GenericApiEndpointMethods[endpoint.method] !== undefined
  &amp;&amp; ApiEndpointTypes[endpoint.apiEndpointType] !== undefined
  &amp;&amp; endpoint.group
  &amp;&amp; typeof endpoint.group.groupPublicKey === 'string'
  &amp;&amp; typeof endpoint.group.groupName === 'string'
  &amp;&amp; typeof endpoint.reason === 'string'
  &amp;&amp; typeof endpoint.isPublic === 'boolean'
  &amp;&amp; typeof endpoint.isActive === 'boolean'
  &amp;&amp; authTypes[endpoint.authType] !== undefined
  &amp;&amp; Array.isArray(endpoint.parameters)
  &amp;&amp; Array.isArray(endpoint.headers);
  }
  </code></pre>
  
  <p>This can get cumbersome and unwieldy. And I don’t want to have to do this for every object I create.</p>
  
  <p>When an endpoint comes into our cloud firebase function, we have to do a bunch of validation on it so that we know when to reject bad data. The shape of the endpoint is one of those validations.</p>
  
  <p>I tried doing this:</p>
  
  <pre><code>Delete req.body.reason;
  req.body[‘extraField’] = ‘xxx’;
  Const endpoint: GenericApiEndpoint = req.body;
  console.log(‘endpoint =‘, endpoint);
  </code></pre>
  
  <p>But Javascript doesn’t care. It will accept an endpoint without reason (a mandatory field) and with extraField (a non-existent field in the model) and assign it to an object typed as GenericApiEndpoint. Endpoint prints out without reason and with extraField.</p>
  
  <p>I also tried:</p>
  
  <pre><code>Const endpoint = &lt;GenericApiEndpoint&gt;req.body;
  </code></pre>
  
  <p>…but Javascript doesn’t care about that either.</p>
  
  <p>Does anybody know of a simple way to validate the shape of objects in Javascript?</p>