简体   繁体   中英

Typescript using the Parameters<> Utility Type

I'm trying to use Parameters<> to imitate a function with a wrapper function. I thought something like the below would work and I was hoping to understand why it doesn't. The "spawn" method has overloads, I'm assuming Parameters<> is using the params from the function implementation, ie 1 required and 2 optional params.

import { spawn } from "child_process"

function spawnWrapper(...args: Parameters<typeof spawn>) {
    spawn(...args)
    // ...
}

spawn("ls", ["-la"]) // => TS compiler is happy

spawnWrapper("ls", ["-la"]) // => Expected 3 arguments, but got 2.

According to the IntelliSense box, there are 20 overloads for spawn . Here's a link to the lines in the current declaration file:

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/122c5336ff41ad8b0e3ebddc4e96e34facaaf8e5/types/node/child_process.d.ts#L650-L789

Also, here's a link to the API docs for the current Node LTS version:

https://nodejs.org/docs/latest-v16.x/api/child_process.html#child_processspawncommand-args-options

Depending on what exactly you want to support (and what kind of DX you're trying to implement), you'll need to handle fewer or more of the overload cases with your wrapper.


If you want to support only the case in your example, you can define a 2-member tuple for the parameters, like this:

import {spawn} from 'child_process';

function spawnWrapper (...params: [
  Parameters<typeof spawn>[0],
  Parameters<typeof spawn>[1],
]) {
  return spawn(...params);
}

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