Skip to content

Instantly share code, notes, and snippets.

@ASafaeirad
Created June 12, 2019 22:53
Show Gist options
  • Select an option

  • Save ASafaeirad/591cb58a9c17cc3605ee65e1f09ac60b to your computer and use it in GitHub Desktop.

Select an option

Save ASafaeirad/591cb58a9c17cc3605ee65e1f09ac60b to your computer and use it in GitHub Desktop.
Javascript dynamic type system decorator
const typeDecorator = (type) =>
(target, key, descriptor) => {
let value;
return {
enumerable: true,
get: function () { return value; },
set: function (newValue) {
const newType = typeof newValue;
if (newType !== type || newType === 'undefined') {
const error = `invalid type for "${key}", expect "${type}" but get "${newType}"`;
throw Error(error);
}
value = newValue;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment