Putting the Dynamic back into TypeScript
The Web Dev Zone is brought to you in partnership with Mendix. Discover how IT departments looking for ways to keep up with demand for business apps has caused a new breed of developers to surface - the Rapid Application Developer.
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.
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.
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.
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,