简体   繁体   中英

Return same object as argument

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?

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

Generics. The constraint is the return is same as argument eg

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM