Clean TypeScript code with type guards
Do you search for a cleaner code in TypeScript? You can start by using TypeGuards!
Read moreA singleton is a common design pattern in object oriented programming.
This pattern forces the program to have only one instance of an object at a time.
In modern JavaScript and TypeScript, lot of developers could create a singleton writing a class and then exporting a single instance of it.
class Foo {
constructor() {
this.bar = 10;
}
decrement() {
this.bar--;
}
increment() {
this.bar++;
}
}
export default new Foo();
Guess what, you are doing it wrong.
In node.js modules are singleton by nature, so you does not need to write a class to it!
Let's rewrite it again:
let bar = 10;
function decrement() {
bar--;
}
function increment() {
bar++;
}
export default {
bar,
decrement,
increment,
}
Doing this way is simple and you do not have to create a class (and the machine will not have to instance a unused prototype) and you will avoid to create new instance of Foo
class.
Do you search for a cleaner code in TypeScript? You can start by using TypeGuards!
Read moreBored of checking incoming JSON data from clients? Try with a middleware and typeguards!
Read moreWhat if we are making a great mistake? Finding value where there is some.
Read more