Andrius Naruševičius
Andrius Naruševičius

Reputation: 8578

How to pass two parameters into function or none in typescript?

I wanted to improve a function that just returns a status. It does not accept any other parameters except a logger and a message to log with it.

export function status(logger: Logger, reason: string) {
  logger.info(reason);
  return {
    result: 'ok'
  };
}

However I want to make the parameters optional so if I don't want to log anything, I don't need to pass anything. Thus I changed it like this:

export function status(logger?: Logger, reason?: string) {
  reason && logger?.info(reason);
  return {
    result: 'ok'
  };
}

However I can still provide a logger but not provide a reason and I don't like that. I want this function to accept either both or no parameters. So I tried something like this:

export function status(param: {logger: Logger, reason: string} | {} = {}) {
  param?.logger.info(reason);
  return {
    result: 'ok'
  };
}

However now I am getting TS2339: Property 'logger' does not exist on type '{} | { logger: Logger; reason: string; }'.   Property 'logger' does not exist on type '{}'. and I do not know how to do this correctly. I would want to learn - can you please explain how this could be achieved?

Upvotes: 0

Views: 2637

Answers (1)

fjplaurr
fjplaurr

Reputation: 1950

EDIT: You dont provide how the type Logger looks like. But seeing your code, I assume it must be something similar to this:

type Logger = { info: (someInfo: string) => void }

Define the type of the params that the status function receives:

type paramsStatus = {
  logger: { info: (someInfo: string) => void },
  reason: string,
}

You make params optional with ? operator. Since logger and reason are mandatory (see the type above), they both have to be passed to the status function. Both or neither of them, both ways are correct.

export function status(params?: paramsStatus) {
  params && params.logger.info(params.reason); //If params exist, then log the info
  return {
    result: 'ok',
  };
}

Upvotes: 1

Related Questions