Home > Blockchain >  Should functions be responsibile for checking if required params exists at runtime?
Should functions be responsibile for checking if required params exists at runtime?

Time:09-08

With TypeScript you have no runtime guarantees, so I was wondering where to actually check whether or not a function param exists.

Trusting TypeScript, assuming someRequiredParam will never be undefined or null:

function myFunc(someRequiredParam: { foo: string, bar: string }) {
  return JSON.stringify(someRequiredParam);
}

This will work fine at compile time, but could blow up at runtime.

NOT trusting TypeScript, but then why ever use required params?

function myFunc(someRequiredParam: { foo: string, bar: string }) {
  if (isText(someRequiredParam?.foo) && isText(someRequiredParam?.bar)) {
    return JSON.stringify(someRequiredParam);
  }
}

Seems redundant to have these runtime checks when you already have typed them as required.

In the above case I might as well define the param and its nested props as optional

function myFunc(someRequiredParam?: { foo?: string, bar?: string }) {
  if (isText(someRequiredParam?.foo) && isText(someRequiredParam?.bar)) {
    return JSON.stringify(someRequiredParam);
  }
}

But then you lose the strong typing at dev/compile time, which doesn't seem right.

Of course you could also check if the values exist before passing them on to the function, however relying on that doesn't seem right either.

I think it's a lot easier to work with a sound type system you can trust, like e.g. the one in ReScript, where you won't have these runtime errors after your code compiles, because the language forces you to handle cases equivalent to null/undefined in TS/JS.

But I'm very curious to know, how people utilize TypeScript so it's not giving you a false sense of security by only catching errors at compile time. Is using a lot of type guards what people typically do? And do you use them inside functions to check if required params exist at runtime?

CodePudding user response:

If you are within the boundaries of your own module and it is safely-typed in TypeScript then you can trust your type signatures.

If you are interacting with another system, or a server, then definitely add checks when data from outside sources moves into your modules.

TypeScript is mostly sound. In my experience, in production type errors are fairly rare if you pay attention to boundaries.

  • Related