A great benefit from TypeScript is, that it has semantics and syntax that is similar to that C#. TypeScript has classes with methods, properties and inheritance. There are modules, which are similar to namespaces. However, there are some quirks, that makes TypeScript behave differently to what a C#-coder would expect. Lets get back to those and start with a simple example.
Modularize the code
For this first example, lets recall the code snippet for previous post doing a simple field hide/show. The obvious would be to create a method in a class within a module, like below.///<reference path="Xrm.d.ts"> module DKCRM { class HideField { hideField() { ... } } }
There are two reason why that would not work.
- The class is internal to the module. Compare it to a private class in C#
- In CRM form events it is only possible to execute function by name, i.e. a class cannot be instantiated.
///<reference path="Xrm.d.ts"> module DKCRM { export class HideField { static execute() { var instance = new HideField(); instance.hideField(); } hideField() { var phone: string = Xrm.Page.getAttribute('telephone1').getValue(); if (phone == null) { Xrm.Page.getControl('fax').setVisible(false); } else { Xrm.Page.getControl('fax').setVisible(true); } } } }
Getting it to work in CRM is then only a matter of uploading the generated JavaScript-file as a web resource and call DKCRM.HideField.execute function from the form event.