Conditionally making optional properties mandatory in typescript

A common case in applications is to work with types where certain properties are nullable. However, it is also common to need derived types of these same types which are stricter around nullablity of properties.

Let’s imagine a note taking app: We have a `Notebook` type where `id` is nullable because unsaved notebooks haven’t been assigned an `id` yet. However after saving it, we know for a fact that a `Notebook` instance will have an `id` and ideally we shouldn’t have to say `!` in the rest of the application.

So, in this post we will explore a generic way to derive types like `SavedNotebook` where certain properties are conditionally mapped to non-optional.

Continue Reading →

Deriving interfaces from classes in TypeScript

Most object oriented programming languages encourage the pattern of Programming to an interface. TypeScript supports this of course, you can create one or more interfaces, and then define classes (or factories) that generate instances of this interface.

However, as the linked article above points out, programming to an interface is sometimes overused when the programmer anticipates the possibility of multiple concrete implementations in future although there may exist just one at the time of implementation.

But, until these multiple implementations are actually required, these single-implementation interfaces continue to increase maintenance overhead, because every time we need to introduce a new member, we need to modify two places. Sure, the tooling helps with this but it still not ideal.

Also, relying on just the concrete implementation is not ideal because TypeScript compiler service doesn’t yet have a good mechanism to bulk-replace all usage of a concrete implementation with the corresponding interface should we need multiple implementations in future.

So, in this post we explore two features of typescript that may help us with this.

Continue Reading →

Dealing with circular type references in Mobx-state-tree

A frequently occuring issue when creating interrelated MST models, is that of circular type references.

Usually we don’t don’t have to explicitly define interfaces for our models, because they can be inferred for us through the APIs exposed by MST. However, when defining models that depend on each other, this falls short because TypeScript’s type-inference is not good enough to circular dependencies.

This post outlines how we can augment the inferred types in MST to resolve such cases.

Continue Reading →