Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I restrict a function to be pure in TypeScript?

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?

like image 215
gsamaras Avatar asked Aug 23 '17 08:08

gsamaras


People also ask

What is a pure function in TypeScript?

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.

Should functions always be pure?

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.

Are pure functions immutable?

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.

How do you pass a function as a parameter in TypeScript?

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.


1 Answers

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.

like image 99
Madara's Ghost Avatar answered Sep 22 '22 12:09

Madara's Ghost