Last_Node_Standing
Last_Node_Standing

Reputation: 429

How to return Promise<Type> when value to return is of type Promise<Type | null>? Typescript server

I'm trying to return a user of type UserRecord after saving to database, but getting a linting error because getUserByUuid returns Promise<UserRecord | null> so the linter is returning an error because I'm trying to return a type <UserRecord | null> for createUser which returns Promise<UserRecord>. I've tried to type assert it user! but it's not working. I'm checking it in the null check right before the return but the linter isn't picking it up. What's the best way to handle this situation?

  createUser = async (params: any): Promise<UserRecord> => {
    try {
      
      await insertUser(params);
      const user = this.getUserByUuid(params.uuid);
      if (user === null) {
        throw new Error("user failed to save");
      }
      return user;
    } catch (e) {
      throw e;
    }
  };

Upvotes: 0

Views: 417

Answers (1)

Nadia Chibrikova
Nadia Chibrikova

Reputation: 5036

The problem is that you return a Promise, which is never going to be null, for your code to work you need to await getUserByUuid

const user = this.getUserByUuid(params.uuid);//user is Promise<UserRecord|null>

vs

const user = await this.getUserByUuid(params.uuid);//user is UserRecord|null - this should work

Upvotes: 1

Related Questions