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.

TypescriptCli Tooling

Code

typescriptsnippet
19 lines
// 变参元组:包装函数时参数列表类型原样转发,调用侧不丢失签名
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

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.