2

I'm trying out my first Cloud Function following this guide (https://www.youtube.com/watch?v=qZ1EFnFOGvE&list=PL55RiY5tL51r5jyQoPZhwLueLpPeAV6P9) which is written in JS, but instead writing in Typescript.

I have created the following:


// // Start writing Firebase Functions
// // https://firebase.google.com/docs/functions/typescript
//
 export const helloWorld = functions.https.onRequest((request, response) => {
  
  if (request.method !== 'POST') {
      return response.status(500).json({
          message: 'Not allowed'
      });
  }

  response.status(200).json({
      message: 'Hello World!'
  });
 });

However, the linter gives me the following error:

Argument of type '(request: Request, response: Response) => Response | undefined' is not assignable to parameter of type '(req: Request, resp: Response) => void | Promise'. Type 'Response | undefined' is not assignable to type 'void | Promise'. Type 'Response' is not assignable to type 'void | Promise'. Type 'Response' is missing the following properties from type 'Promise': then, catch, [Symbol.toStringTag]

I am unsure how to amend the code.

1 Answer 1

3

Typescript expects a function that returns either nothing or a promise. However, you are returning the response object in the if statement, and undifined if the condition isn't true. An easy way to fix it in this case would be:

export const helloWorld = functions.https.onRequest((request, response) => {

  if (request.method !== 'POST') {
    response.status(500).json({
       message: 'Not allowed'
    });
  } else {
    response.status(200).json({
      message: 'Hello World!'
    });
  }

});

If you want to "return" out of the function instead of using an else statement, you can just do this:

export const helloWorld = functions.https.onRequest((request, response) => {

  if (request.method !== 'POST') {
    response.status(500).json({
       message: 'Not allowed'
    });
    return;
  }
  
  response.status(200).json({
    message: 'Hello World!'
  });

});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.