NodeJS allows you to set process-level global values that can be accessed in any module.
In general I would consider implicitly sharing global values between modules a bad practice, however in certain situations it can be a pragmatic choice.
Assigning globals using pure JavaScript is straightforward, making them work with TypeScript is another thing. Let’s dive in.
The built in Array.filter method cannot be used to filter array items in a type safe way. To exclude some items on the type level we would need a typecast. Are there any better alternatives?
Oranges only please
To demonstrate this, let’s say we have a basket of apples and oranges. We want to make some fresh orange juice. And of course all that using TypeScript.
Our first approach might look like this:
1 2 3 4 5 6 7 8 9 10
// Let's pretend this function is a juice squeezer const squeezeJuice = (fruits: Array<'orange'>) =>'orange-juice';
There are situations where one would like to cover all possible values of a variable using conditional cases. A good example of this situation is a typical reducer function. Let’s consider an example of a counter with simple actions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
type Action = 'increment' | 'decrement';
functionreducer(state: number, action: Action): number{ if (action === 'increment') { return state + 1; } else { return state - 1; } }
So far so good. Now, let’s see what happens when another kind of action is added – 'reset', which in effect should set the counter back to 0.
1
type Action = 'increment' | 'decrement' | 'reset';
Now, let’s assume that you forgot to update the reducer function. Considered example is overly simplistic, but maybe the codebase is large and you didn’t even know about the existance reducer at all.