function required() { return function (target: any, name: string) { if (!target.constructor.requiredFields) { target.constructor.requiredFields = []; } target.constructor.requiredFields.push(name); }; } class Mock { @required() public id: number; public name: string; constructor(name: string) { this.name = name; } validate() { let valid = true; let field; for (field of (<any>Mock).requiredFields) { valid = valid && this[field] != null; } return {valid, field}; } save() { const validateRslt = this.validate(); let msg; if (!validateRslt.valid) { msg = "Missing required field - "+validateRslt.field; } else { msg = "Data saved - "+JSON.stringify(this); } window['target'].innerText = msg; } } function main() { const mock = new Mock('test'); // Comment out for making the validation pass // mock.id = new Date().getTime(); mock.save(); } main()
<div id="target"></div>