HTML5 Zone is brought to you in partnership with:

Derik Whittaker is a Software Architect who specializes in all things .Net. Derik has been building enterprise systems on top of the .Net technology stack for over 12 years and along the way has picked up a thing or two about how to create killer systems. During his 12 year career Derik has worked in many different industries ranging from Marking, Healthcare, Retail, Insurance, Automotive and Online Entertainment. Currently Derik is working for a Technology startup (VStrator) in Raleigh North Carolina helping them build out a best of breed technology solution which will enable their users to create world class coaching solutions. Derik believes that the job of a developer is more than just turning syntax into working 1’s and 0’s. Derik is a DZone MVB and is not an employee of DZone and has posted 22 posts at DZone. You can read more from them at their website. View Full User Profile

Putting the Dynamic back into TypeScript

05.08.2013
| 2282 views |
  • submit to reddit

One of the really powerful features that TypeScript brings to the JavaScript world is some Static Typing, even if it is only at code/compile time.  With TypeScript I can say that an object is of a certain type which implies there are only a limited set of properties/methods available to me.  This is great, but it does limit the core power of JavaScript and dynamic languages in general.

Given the static nature of TypeScript, (yes I can choose to ignore this feature, but why?) which I want in most cases, the following will cause me compile time issues.

image

The reason this is causing me issues is because MemberInitContext does NOT contain a LoadChoachingStaffStats property, but I know that the caller may provide an object which does contain this object.   Below is my definition for MemberInitContext.

image

Given I know this property MAY be provided at runtime I have a decision to make.  I can do any of the following to resolve my build errors.

  • Add the property to the MemberInitContext
  • Create a inherited type which contains this property
  • Change my constructor to take an ‘any’ rather than a type
  • Add the dynamic back into TypeScript

I am going to choose the last option here, but how?  Simple, by redefining the variable to an any INSIDE my constructor as below.

image

By declaring my type as an ‘any’ TypeScript is happy and lets me hack away and complete my tasks.

Long story shot is that even though TypeScript tries to impose Static typing, which is AWESOME in most cases, you can still force it back to dynamic if you want.

Till Next Time,




Published at DZone with permission of Derik Whittaker, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)