Eslint force to consume return values

Viewed 73

I am looking for a typescript or eslint rule I can use to force using return values from functions. Eg

const getNum = () => 12

The rule should allow me to call it and store the value like

const a = getNum()

But I should not be able to do

getNum()

I am currently experimenting with libraries like neverthrow or ts-results and at this moment if I return a result<ok, err> the consumer is still able to call a function without handling errors, especially when the ok part is just an success result.

1 Answers

The rule that's closest to what you're looking for is no-unused-expressions, but based on your question it seems like you're already aware of that rule. That webpage includes a rationale of why it allows something like getNum() on its own; a function might return a value while also having some side effects. Blanket disallowing calling functions without storing the result would end up with lots of code that looks like:

const unused = callForSideEffects();
// unused is... unused

This is wasteful (since you're storing a value that's not ever used) and confusing (why store a value if it's not ever used?)

Related