Sam Chung
Sam Chung

Reputation: 65

Typescript Return Types: explicit-module-boundary-types error

I'm trying to adjust from moving to Typescript from Node so I've setup a bunch of eslint's to help me:

I can't seem to understand the following eslint error:

Missing return type on function. eslint@typescript-eslint/explicit-module-boundary-types

This is my code, the error is raised on the sns function.

const sns = ({config, logger}: SNSInterface) => {
  const client = new SNSClient({endpoint: config.sns.endpoint});

  const publish = async ({message, topicArn}: PublishInterface) : Promise<void> => {
    const command = new PublishCommand({
      Message: JSON.stringify(message),
      TopicArn: topicArn,
    });
    logger.debug({message, topicArn}, 'Publishing SNS Message');
    const data = await client.send(command).catch((err) => {
      logger.error(err, 'Failed to send Topic ARN');
      throw err;
    });
    logger.debug({data}, 'Publishing SNS Message Results');
  };

  return {
    publish,
  };
};

export default sns;

While I can resolve it by adding:

interface SNSReturnInterface {
  publish: ({ message, topicArn }: PublishInterface) => Promise<void>;
}

const sns = ({config, logger}: SNSInterface): SNSReturnInterface => {

Is this really the best way to do this? I would think that Typescript should be fine with inferring this? If I wanted to add a parameter to the publish function, would that mean I would have to change the ReturnInterface definition every time too? I don't want to turn off the rule unless necessary. Appreciate any advice!

Upvotes: 0

Views: 6878

Answers (1)

Travis Valenti
Travis Valenti

Reputation: 148

The explicit-module-boundary-types rule means that you need to explicitly tell Typescript what is being returned by the sns function.

In your sample you've defined the type of publish, but you haven't explicitly defined the return type of sns (return { publish }).

Typescript itself is completely okay with inferring these types, but the rule wants you to be explicit, which is why your second sample works.

If you want to allow Typescript to automatically infer these return types then you should be fine turning off that eslint rule.

Alternatively, if you'd rather keep the rule, but only define the types once, you can define the return types like you've done in your second sample, and omit them from the other places. This way you've got an explicit definition on your boundary type (the exported sns object), which Typescript can use to infer the type of publish.

Upvotes: 1

Related Questions