#StringUtils

6 messages · Page 1 of 1 (latest)

silver eagle
#

I'm wondering if there are StringUtils similar to Java to perform some of the repetitive functionality. For example, isEmpty() needs to check for null, as well as undefined, as well as "".
I did find this project:
https://github.com/tejzpr/stringutils

But I'm curious about how it's done in a culturally TypeScript way?

public constructor(eventId: UUID, eventType: string, isJson: boolean) {
      if (!eventType)
          throw new Error("Type cannot be null, empty or whitespace");

      this.eventId = eventId;
      this.eventType = eventType;
      this.isJson = isJson;
  }
GitHub

A JavaScript clone of Apache's Java StringUtils, implemented using TypeScript - tejzpr/stringutils

north belfry
#

null, undefined, and '' are all falsy in JS, so simply doing if (!str) throw ... will suffice, no need for a utility function.

silver eagle
#

Thanks!

calm veldt
#

however this is not exactly good practice - what is falsy and truthy are regular JS pitfalls and one of the earliest things typescript had over java was explicit nullability. The way you're typing your constructor you don't need to check for null or undefined, only for "" since it's already guaranteed to be a string and not "maybe a string" (assuming you have strict typechecking set to true which you absolutely should)

north belfry
#

(strictNullCheck is the one, which should be turned on automatically if you have strict turned on)

#

But yeah that’s a point I missed, in TS null and undefined are explicit separate types, so when you have eventType: string it already cannot be null or undefined and you don’t have to defensively null check everywhere.