Is there a way to allow a function to be pure only (thus not accepting the function to be non pure) in TypeScript? If yes, which?
Pure functions In simple terms, a pure function doesn't have any hidden inputs or outputs and always returns the same output for the same input. This makes it perfect for unit testing since you can always expect the same behavior for a given test data.
A dead giveaway that a function is impure is if it makes sense to call it without using its return value. For pure functions, that's a noop. I recommend that you favor pure functions. Meaning, if it is practical to implement a program requirement using pure functions, you should use them over other options.
Pure functions don't modify their input. They treat the input values as immutable. An immutable value is a value that, once created, cannot be changed.
Similar to JavaScript, to pass a function as a parameter in TypeScript, define a function expecting a parameter that will receive the callback function, then trigger the callback function inside the parent function.
You might be able to write a few TSLint rules to catch most of the common cases (access to outside variables, for example), but checking something like that is nigh impossible, so there's no way to actually know 100%.
You (and your team) still have to be disciplined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With