Provide Single Source of Truth for TypeScript Types using Lookups

Tomasz Ducin
InstructorTomasz Ducin
Share this video with your friends

Social Share Links

Send Tweet

Using lookups in TypeScript for function parameter type definitions and other places can be useful for values you know might change over time. This will prevent you from having to change the type of the object itself as well as any function or component that needs to receive data about that object.

[00:00] Another technique that can simplify maintenance of our TypeScript code basis in the long run is avoiding copying the types of certain properties of certain entities. So instead of copying, for instance, that ID of an employee type is a number and using explicitly the number type, [00:19] we're going to look it up. We're going to relate to it directly and explicitly. So for instance, if we have a find employee by ID function, then the ID parameter that could be used is, of course, number because that's the type of the employee's ID property. But if this one changes, [00:40] then we have a desynchronization between our function and the model definition. So what we want to do instead is basically look it up using the index notation in TypeScript. And whenever the type of the ID changes as we're here changing from [01:00] number to string, which could happen in a system, for instance, when going to cloud, then all the usages of the ID or all other properties could be automatically reflected. One additional advantage that we gain from this approach is that when we change the shape of the entity type interface that we're working with, and let's [01:20] say that we rename the ID property that we relate to into, let's say, GUID, then TypeScript would obviously synchronize between our model [01:40] definition and the way we want to use the model within our functions and methods, such silly mistakes are going to be automatically caught and we're forced to adapt to what our model is. Note that this approach shouldn't be used universally. For instance, there are properties such as the first name and last name, which are [02:00] strings, and it's really difficult to imagine that a first name would be anything different than a string. So whenever we see a probability that a definition of a certain property could change, this could be useful, but don't apply it everywhere universally.