typescript return null found pattern question

Viewed 39

If i have an interface User like so:

export interface User {
  username: string;
  hash: string;
}

and i have a method signature that looks like this that returns a User typically from a database

function getUser(username: string): Promise<User>

Then in a calling program, I'd want to do something like this:

  const user: User = await getUser(username);
  if (user && (await passMatch(password, user.hash))) {
    return genToken();
  }

What are some popular patterns of return types and validation combos on user not found?

In java (right or wrong) i'd return null and do a null check.

Is a throw not found error and catch it, a good pattern? I can't reconcile not finding one is not an error.

1 Answers

If not finding a user is not an error then you should change the method signature like this:

function getUser(username: string): Promise<User | null>

Then inside the calling method(s) you should throw an error if it suits the method's rule (also you wouldn't need the : User since its implicit by the method):

  const user = await getUser(username);
  if (!user) throw new Error...
  if ((await passMatch(password, user.hash))) {
    return genToken();
  }

Or if you don't actually need to throw an error, just keep it the way you are doing inside the method.

Also I would probably change that await inside the if:

  const passwordCorrect = await passMatch(password, user.hash);
  if (!passwordCorrect) {
    throw...
  }
  return genToken();

PS:

If you want to use good patterns and enforce them in your project I strongly advise you to use lint. I recommend the airbnb typescript config:

https://www.npmjs.com/package/eslint-config-airbnb-typescript

Related