DEV Community

Discussion on: A JSDoc in TypeScript's Clothing

Collapse
 
thejaredwilcurt profile image
The Jared Wilcurt • Edited

A while back I had an idea (mostly inspired by Vue's prop type approach) of a runtime version of type checking. Here is a quick sketch of it:

const typeError = function (err) {
  throw err;
};

const hString = new Interface({
  type: String,
  required: false,
  default: 'Hello',
  validation: function (value) {
    return value.startsWith('H');
  }
});

function greetTarget (greeting, target) {
  Interface.validate(greeting, hString, typeError);
  try {
    Interface.validate(target, {
      type: String,
      required: false,
      default: 'World'
    });
  } catch (err) {
    console.log('The value supplied for target does not match interface. Falling back to default: ', err.default);
  }

  return greeting + ' ' + target;
}

greetTarget('Hey', 'buddy');
Enter fullscreen mode Exit fullscreen mode

Pros:

  1. Allows for runtime checking
  2. Allows for defaulting values
  3. Allows for custom validation
  4. Allows for multiple types via type: [Number, String] or type: [Array, Set]
  5. Easily extensible. For example you could add a strip: true to the object to tell WebPack or whatever to strip out all type checks of that Interface. Or to strip out all by default unless they have a keep: true. Meaning you can define compile-time-only and run-time specific uses to reduce bloat of your builds.
  6. Can take a defined interface or an object. So object definitions could be reused and ... rest/destructured
  7. Easily reusable. You could have an entire file of validators like export const H_STRING =. Interface validation libraries could be pulled in and used and easily tree-shaken
  8. Can be applied to arguments in a function, or just any one-off variable
  9. Because this is just plain JS it is compatible with everything (JSDoc, TS, React, Vue, Node, IE, whatever).
  10. Linting could be used to enforce usage (like with JSDocs linting), or to require either required or default be set (like in Vue's proptypes linting)
  11. The functions used in the validation could be unit tested easily with tools like Jest.
  12. Could be adopted by TC39 for ES20XX without ANY NEW SYNTAX CHANGED, and easily polyfilled to any previous browser or Node version.
  13. Even if built in to the browser, it would be easily modified or tweaked due to JS's prototypal nature, to add unique features for specific use cases.
  14. Codemods could be used to convert existing TS or JSDoc projects over to this approach

My sketch is rough, but you get the idea. If you want to take a stab at creating a proof of concept let me know and I'll be a beta tester. The function names used can be completely different too. It's not a blueprint, just an idea.

Collapse
 
sergioness profile image
Serhii Krasnovidov

you may want to give gitlab.com/dejawu/ectype a go