#How can I make a "type check wrapper" nicer? (I can't explain my problem clearly in one sentence)

16 messages · Page 1 of 1 (latest)

noble parcel
#

It's a bit difficult for me to explain this question clearly in words.
So i've writed a demo

let initialized = false;
let counter: number | null = null;
export function initializer(...args: any){
  // ...
  counter = 1;
  initialized = true;
}
function initCheckWrapper(func: (...args: any) => any) {
  return (...args: Parameters<typeof func>) => {
    if (initialized !== true) 
      throw new TypeError('module is not initialized');
    return func(...args);
  }
}

function count() {
  counter++; // "counter" could be null
}
const wrappedCount = initCheckWrapper(count);
export { wrappedCount as count };

how to make counter not to be a number | null but just number in initCheckWrapper(count) scope?

plain burrow
#

I think the short answer is probably "there isn't a way to do that" - in some cases you could handle this sort of situation by passing the value into the 'initialized' context, something like:

function count(counter: number) {
   return counter + 1;
}

but this doesn't work if you want to directly mutate the value.

#

Realistically, this is the sort of pattern I use from time-to-time:

type Thing = { count: number }
let thing: Thing | undefined = undefined;

function expectThing() {
  if(thing === undefined) throw new Error("Thing is not initialized");
  return thing;
}

export function initialize() {
  thing = { count: 0 };
}

export function count() {
  expectThing().count += 1;
}
#

I think this has basically the same behavior as your version - the exposed function throws a "not initialized" error if you try to count without calling initialize first.

noble parcel
#

i c...

plain burrow
#

The main difference is that expectThing() actually checks the thing you care about (rather than checking a separate initialized variable) and then it returns the narrowed value to the code that needs it.

noble parcel
#

well

#

so

#

I can maybe

#

use a "global object getter"

#

call it each time I need

#

tks

noble parcel
noble parcel
#

!resloved

#

?