title: Typescript object runtime check with a twist
body: <p>I have a server application that gets input data, as javascript objects. I need to check whether these data fullfills the requirements like: </p>
  
  <ul>
  <li>it has required fields defined by an interface </li>
  <li>these fields are certain types</li>
  <li>the object has only the listed fields, nothing else</li>
  </ul>
  
  <p>I've found 2 libraries that very helpful for the goals:</p>
  
  <p>Library <a href="https://github.com/pelotom/runtypes" rel="nofollow noreferrer">runtypes</a> and <a href="https://github.com/gcanti/io-ts/blob/master/Type.md#recursive-types" rel="nofollow noreferrer">io-ts</a> </p>
  
  <p>For example using <strong>runtypes</strong> i can create runtime types:</p>
  
  <pre><code>const PropSchema = Record({
      uid: String,
      name: String,
      timestamp: Number
  });
  </code></pre>
  
  <p>And I can create a static type from PropSchema:</p>
  
  <pre><code>type PropSchemaInterface = Static&lt;typeof PropSchema&gt;;
  </code></pre>
  
  <p>From now on, I can use it as if it was an interface, typescript will warn if an object is invalid:</p>
  
  <pre><code>let props: PropSchemaInterface = { // this is invalid, because name is not a string
      uid: "31293-a7aa216982678",
      name: 4,
      timestamp: (new Date()).valueOf()
  }
  </code></pre>
  
  <p>and check if an object fulfills PropSchema:</p>
  
  <pre><code>PropSchema.check(props); // returns true
  </code></pre>
  
  <p>but</p>
  
  <pre><code>PropSchema.check({
      uid: "12"
  });
  </code></pre>
  
  <p>throws an error because name and timestamp does not exist in the provided object. That's very nice. But I really need to check whether the input object has only the fields defined in PropSchema, and nothing else. I could not find a way how to, because using this schema:</p>
  
  <pre><code>PropsSchema.check({
      uid: "123-123123123",
      name: "John Snow",
      timestamp: 123123123,
      someKey: "somevalue"
  });
  </code></pre>
  
  <p>also returns true, as the provided object fulfills PropSchemaInterface, but for me it's an invalid object, because it has an unknown key: someKey. I could not find any library that can verify it for me.</p>
  
  <p><strong>Is there any way to validate objects the way I want?</strong> Runtypes is a really useful library as it's possible to have both <em>Runtime</em> and <em>Compile time</em> validation using the same descriptor (<strong>PropSchema</strong>), and I don't need to define it twice, but I could not figure out how to check for invalid object members. IO-TS has the same ability, but i did not try it so far.</p>