Efficient Typescript

submited by
Style Pass
2024-10-20 00:00:05

One of the most useful ways that a type-system can work is by preventing a class of errors. The simplest way to interpret that is that it will prevent you from using a number where you need a string, but there’s more to it. Typescript allows you to encode more complex restrictions into the type-system, so the compiler can help you avoid making some mistakes.

It’s an issue I see frequently, even in popular library code. For example, let’s take this snippet from react-query’s documentation:

There is here an implicit constraint that if isPending or error is present, then data isn’t. But ensuring that constraint is a task that’s left to you, the fallible programmer. Typescript actually allows you to turn that implicit constraints into an explicit one, which means the compiler could be doing work so that you don’t have to think about it.

Some commenter pointed out that react-query is a bad example because it can represent more complex situations with its different flags. I’ll leave the example as is, because the example is good, even if contrived. The library could also reserve a different function for more complex scenarios, e.g. useQueryWithRetainedData to keep data alive while re-loading, which would in turn allow for stronger type constraints in the common scenarios.

Leave a Comment