Platinum Partner
css,html5,javascript,tips and tricks,typescript

Putting the Dynamic back into TypeScript

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 {{ articles[0].authors[0].realName }}, DZone MVB. (source)

Opinions expressed by DZone contributors are their own.

{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}