Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Non-Empty String Type #946

Open
roryabraham opened this issue Aug 27, 2024 · 1 comment
Open

Non-Empty String Type #946

roryabraham opened this issue Aug 27, 2024 · 1 comment

Comments

@roryabraham
Copy link
Contributor

roryabraham commented Aug 27, 2024

It seems pretty common that we run into issues with a string being empty when it's not supposed to. These are some common issues I see:

  1. An API parameter is meant to be a string, but an empty string isn't valid.
  2. We mean to default an empty string to something else, such as '-1', but our ESLint config encourages us to use nullish coalescing ?? instead of ||. Obviously these don't work the same in cases where you have an empty string.

anyways, my suggestion is to create a type called NonEmptyString. According to this Stackoverflow, the best way to accomplish this is with a very verbose template literal with any non-empty character followed by a string

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • The funding will be given to active contributors.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar
@sindresorhus
Copy link
Owner

Could be useful, but someone has to prove that it works in practice without too many downsides.

Some alternatives:

type NonEmptyString = string & {0: string}
type NonEmptyString = string & {length: Exclude<number, 0>};
type NonEmptyString = string extends '' ? never : string;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants