0

This is probably an anti-pattern, but I want to return the same object as an argument, in this case like so:

const handleConnection = (s: net.Socket): net.Socket => {

  s.pipe(createParser()).on('data', (d: any) => {

    log.info(chalk.green.underline('dygrep server response:'));

    if (d && d.lastMessage) {
      process.stdout.write(prompt);
    }

  });

  return s;

};

so what would be ideal is to do something like this:

const handleConnection = (s: net.Socket): s => {

  s.pipe(createParser()).on('data', (d: any) => {

    log.info(chalk.green.underline('dygrep server response:'));

    if (d && d.lastMessage) {
      process.stdout.write(prompt);
    }

  });


  return s;

};

but yeah that's not quite right - how do I tell TypeScript that I am returning one of the arguments?

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
  • Are you trying to enforce in compile-time the fact that the argument and return value are not only of the same type, but necessarily the same object? – Cerberus Sep 18 '18 at 04:14

1 Answers1

1

how do I tell TypeScript that I am returning one of the arguments

Generics. The constraint is the return is same as argument e.g.

function handleConnection<T extends net.Socket>(arg:T):T{}

Here whatever is passed in as arg is what is returned.

basarat
  • 261,912
  • 58
  • 460
  • 511