Immutable.js Records in TypeScript

Florian Hämmerle
1 min readJun 9, 2018

At my previous company we used both Immutable.js and TypeScript. They play really well together even if you need to take care to not lose type safety along the way. We use TypeScript with the strict compiler flag turned on which also enables the strictPropertyInitialization flag.

Since the initial / default values of an Immutable Record are taken care of by Immutable the TypeScript compiler complains about uninitialized properties. To circumvent this, you could turn off strictPropertyInitialization but that would also turn it off in all classes not deriving from Record.

The solution to this problem is to explicitly tell TypeScript that the Record’s properties will be always properly initialized by using definitive assignment assertions (!). You can see how this is done in line 14 & 15 in the code snippet below. Also note the readonly modifier since immutable types can not be altered directly.

UPDATE (Apr 27, 2020): As Marcin Fudali mentioned in this comment, there’s now an easier way.

--

--

Florian Hämmerle

raised & based in the Alps • co-founded a digital studio • former CPO at a news company • partner at a software consultancy • into products and innovation