You can also use 'type assertions' to minimise restructuring, eg, the following is the same number of lines as your first example (and compiles to identical code):
const a = A()
a.b = new SubtypeOfB()
(<SubtypeOfB> a.b).attributeOfSubtypeOfB = 123 //worksIsn't this dangerous?
No, you're just telling TypeScript you know what Type it is and it will let you treat it as that Type.
Re:Flow vs. Typescript
by imtringued on Monday June 06, 2016 @05:34AM
(#11845539)
I would recommend you to always do the initialisation through the constructor and preferably make the entire class immutable if you can.
It often feels like they are holding you back more than they help.
I also got such a moment with TypeScript.
Because a.b is type B and not SubtypeOfB and so doesn't have the attribute of SubtypeOfB, but a.b gets its typing from A, which can't be changed on the fly later.The solution was:
Which felt like "Why do I have to restructure my code with extra variables when I clearly know that this object HAS that attribute?!"And Java was full of those problems. Numerous different definitions of the same thing that aren't compatible with each other. Hell, some languages even have different string types.
But yeah, TypeScript is generally chill about most things and the hints it gives me were often right and helped to find the right methods without consulting any docs, which is a huge win, even without the refactoring stuff.