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);
})
};