Structured data

Let's enhance this simple array of contact emails with a little more relevant data. For each of these email addresses, let's assume that we also want to include some text to render within the footer of our page, along with the email addresses. Consider the following HTML <script> tag:

<script type="text/javascript"> 
    var CONTACT_DATA = [ 
        { DisplayText: 'Help',  
        Email: '[email protected]' } , 
        { DisplayText: 'Contact Us',  
        Email: '[email protected]' }, 
        { DisplayText: 'Webmaster',  
        Email: '[email protected]' } 
    ]; 
</script> 

Here, we have defined a global variable, named CONTACT_DATA, that is an array of objects. Each object has a property named DisplayText and a property named Email. If we are to use this array within our TypeScript code, we will need to include a definition of this variable in our globals.d.ts declaration file, as follows:

interface IContactData { 
    DisplayText: string; 
    Email: string; 
} 
 
declare var CONTACT_DATA: IContactData[]; 

Here, we start with an interface definition named IContactData to represent the properties of an individual item in the CONTACT_DATA array. Each item has a DisplayText property that is of the type string, as well as an Email property, which is also of type string. Our IContactData interface, therefore, matches the original object properties of a single item in the CONTACT_DATA array. We then declare a variable named CONTACT_DATA and set its type to be an array of the IContactData interfaces.

This allows us to work with the CONTACT_DATA variable within TypeScript. Let's now create a class to process this data, as follows:

class ContactLogger { 
    static logContactData() { 
        for (let contact of CONTACT_DATA) { 
            console.log(`DisplayText: ${contact.DisplayText},
Email : ${contact.Email}`); } } } window.onload = () => { ContactLogger.logContactData(); }

Here, the ContactLogger class has a single static method named logContactData. Within this method, we loop through all of the items in the CONTACT_DATA array. As we are using the for...of syntax, the contact variable will be strongly typed to be of type IContactData, and therefore will have two properties, DisplayText and Email. We simply log these values to the console. The output of this code would be as follows:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.106.232