Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/39.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 对不同的函数有效地使用TS泛型类型_Node.js_Typescript_Typescript2.0_Tsc - Fatal编程技术网

Node.js 对不同的函数有效地使用TS泛型类型

Node.js 对不同的函数有效地使用TS泛型类型,node.js,typescript,typescript2.0,tsc,Node.js,Typescript,Typescript2.0,Tsc,现在我有一个通用函数类型、一个接口和一个函数: export type EVCb<T> = (err: any, val: T) => void; export interface RegistryData { exitCode: number, npmVersion: string } export const getLatestVersionFromNPMRegistry = function (dir: string, name: string, cb: EV

现在我有一个通用函数类型、一个接口和一个函数:

export type EVCb<T> = (err: any, val: T) => void;

export interface RegistryData {
  exitCode: number,
  npmVersion: string
}

export const getLatestVersionFromNPMRegistry = function (dir: string, name: string, cb: EVCb<RegistryData>) {

  const k = cp.spawn('bash', [], {
    cwd: dir
  });

  k.stdin.end(`npm view ${name}@latest version;`);

  const result : RegistryData = {
    exitCode: null,
    npmVersion: ''
  };

  k.stderr.setEncoding('utf8');
  k.stderr.pipe(process.stderr);

  k.stdout.on('data', d => {
    result.npmVersion = result.npmVersion += String(d || '').trim();
  });

  k.once('exit', code => {
    result.exitCode = code;
    cb(code, result);
  })

};

tsc
的角度来看,这在技术上是可能的,只是不确定它是否是一项功能,是否有办法做到这一点?

EVCb似乎可以工作,问题是什么?它工作吗?即使在函数体内声明了
结果
?我只是认为这是行不通的,你应该一直尝试,有时有效的东西会让你惊讶:-)。您可以对范围内的任何内容使用
typeof
。参数和函数变量共享相同的作用域,因此可以工作。我承认我自己也有点惊讶:-)酷,那么函数变量即使在函数的下一个项中声明了它们?
export type EVCb<T> = (err: any, val: T) => void;

export const getLatestVersionFromNPMRegistry = function (dir: string, name: string, cb: EVCb<typeof result>) {

  const k = cp.spawn('bash', [], {
    cwd: dir
  });

  k.stdin.end(`npm view ${name}@latest version;`);

  const result = {
    exitCode: null,
    npmVersion: ''
  };

  k.stderr.setEncoding('utf8');
  k.stderr.pipe(process.stderr);

  k.stdout.on('data', d => {
    result.npmVersion = result.npmVersion += String(d || '').trim();
  });

  k.once('exit', code => {
    result.exitCode = code;
    cb(code, result);
  })

};