Home > Blockchain >  Should I check for null or undefined when TypeScript will tell other developers it isn't accept
Should I check for null or undefined when TypeScript will tell other developers it isn't accept

Time:08-17

I'm working on a library and the target audience is TypeScript however it is something that is useful for JavaScript and ignoring them will ignore a lot of people.

A lot of the code I'm writing is checking if a value that is NonNullable<T> is in fact null because JavaScript developers can give null or undefined without being told they can't ahead of time.

I'm just not sure if I am expected to add in all of this when giving null or undefined will result in an error regardless, at the expense of every operation for my target audience needing to check against null. If it was a couple times then I wouldn't think much of it but there are method chains with the data passed being validated.

The tooltip when hovering over the method does say clearly NonNullable<T> and this library doesn't have any optional parameters so if it says there is a parameter it needs a value.

I'm bored of writing the same checks which constitutes about 40% of my code, which is even worse considering some parameters are functions so I need to check both if the function is null and if it isn't then if the result of the function is null.

value:NonNullable<T>;
...
public setOr(fn:() => NonNullable<T>) {
  if(fn == null) throw Error("Expected function, not `null` or `undefined`")
  const value = fn()
  if(value == null) throw Error("Cannot accept `null` or `undefined`")
  this.value = value
}

into

value:NonNullable<T>;
...
public setOr(fn:() => NonNullable<T>) {
  this.value = fn()
    //Will implicitly throw an error if `fn` is `null` or `undefined`
}

I am making this primarily for myself, however it would be nice if others would use it and I don't want to make a mistake, but I also want to finish this.

CodePudding user response:

So I think it depends of the typescript support level in the project. If there are a lot of anys or you are using some js-libs, you can definitely think about adding a typeguard for null|undefined and maybe the expected type.

If there are no anys in the whole project and all the apis, libs you are using are also typed, I wouldn't do it. Just because thats why everyone is using typescript. In my opinion it's also better if the guy who is calling your function handle the null value and not your your function itself.

But there are some exception where you should definitely check for null|undefined even if you are not supposed to:

// accessing an array item:
const a = ["a","b"]
const x = a[2] // is undefined but typescript won't tell you that, if the
// compiler option: noUncheckedIndexedAccess is set to false

// accessing an Record
const y:Record<string,string> = {}
const z = y["any"]// is undefined but typescript won't tell you that aswell

  • Related