Variadic Tuples Type Forwarded Arguments
Wrap any function with a timing helper while variadic tuple types forward the original argument and return types, so each wrapped call keeps its own signature.
Code
// 变参元组:包装函数时参数列表类型原样转发,调用侧不丢失签名
function timed<T extends unknown[], R>(label: string, fn: (...args: T) => R): (...args: T) => R {
return (...args: T) => {
const started = Date.now();
const result = fn(...args);
console.log(label, 'took', Date.now() - started, 'ms');
return result;
};
}
const add = (a: number, b: number): number => a + b;
const greet = (name: string, punct: string): string => `hi ${name}${punct}`;
const timedAdd = timed('add', add);
const timedGreet = timed('greet', greet);
// 参数类型各自保留:timedAdd 只接受两个数字,timedGreet 只接受两个字符串
console.log(timedAdd(2, 3));
console.log(timedGreet('Ada', '!'));Output
Captured from a sandboxed run of this snippet in the build pipeline.
add took 0 ms
5
greet took 0 ms
hi Ada!How the snippet works
Variadic Tuples Type Forwarded Arguments comes down to the functions add, greet and timed.
Using it
The entry-point signature is const add = (a: number, b: number)
Key statements
return (...args: T) => {
const started = Date.now();
const result = fn(...args);
console.log(label, 'took', Date.now() - started, 'ms');
return result;
};
const greet = (name: string, punct: string): string => `hi ${name}${punct}`;
const add = (a: number, b: number): number => a + b;
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Is a package install part of the setup?
- No. Installation is unnecessary because only built-in APIs are used. The file defines `add`, `greet`, `timed` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.