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?
Asked
Active
Viewed 2,741 times
21
-
4you decide if a function is a pure function. not typescript.. – Roman Aug 23 '17 at 08:10
-
Here is an article: https://vsavkin.com/functional-typescript-316f0e003dc6 – Mihai Alexandru-Ionut Aug 23 '17 at 08:10
-
3@Roman Ideally a proper type system should be able to do purity analysis. Of course TypeScript isn't that – Bergi Aug 23 '17 at 08:25
-
4At the moment there is only an open issue on GitHub discussing the possibility to add a `pure` modifier: https://github.com/Microsoft/TypeScript/issues/7770 – Stephan Aug 23 '17 at 08:28
-
@Bergi yeah that was my idea.. I am just learning TS now, that's why I am asking..Thanks for the link and all the comments. Stephan yes, I had seen that, but I was asking if there was something standard. – gsamaras Aug 23 '17 at 08:29
1 Answers
8
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.

Madara's Ghost
- 172,118
- 50
- 264
- 308
-
3
-
The answer doesn't seem to be correct. Citation? At the very least, it's possible to detect a subset of cases in which a function is pure, and mark as "impure" when the compiler can't tell one way or another. Voting down, but will undo the downvote if there is a good link and/or explanation. – Max Heiber Sep 27 '18 at 15:42
-
3You may think that `const getX = obj => obj.x` is pure for example, but I can still pass `{ get x() { doSideEffect(); return 42; } }`, you can't win, not in JavaScript. – Madara's Ghost Sep 28 '18 at 09:05
-
5The kind of object you pass to that pure function does not make it impure. That would make all lodash functions like _.forEach, _.map impure, but they are not. They are all pure. If you cause a side effect in the callback function, the callback is impure, but the _.map and _.forEach functions themselves are not impure. – Himanshu Jul 02 '19 at 06:57