Mr T
Mr T

Reputation: 1000

Javascript to Typescript Conversion Error - Cloud Function

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.

Upvotes: 2

Views: 398

Answers (1)

Leonard-H
Leonard-H

Reputation: 62

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!'
  });

});

Upvotes: 3

Related Questions