You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TS入门者如何为类似_.once的函数添加类型定义?

Adding TypeScript Type Definitions to Your once Function

Hey there! Let's walk through how to type your once function so it mirrors Lodash's _.once—supporting any function with arbitrary parameters and return types, while keeping full TypeScript type safety.

The Typed Implementation

Here's the complete typed version of your function, with explanations below:

function once<Args extends any[], Return>(fn: (...args: Args) => Return): (...args: Args) => Return {
  let haveResult = false;
  let result: Return | null = null;

  return (...args: Args) => {
    if (!haveResult) {
      haveResult = true;
      result = fn.apply(this, args);
    }
    // We can safely assert `result` is Return here, since haveResult ensures it's been set
    return result as Return;
  };
}

Breaking Down the Type Definitions

Let's break down what each part does:

  • Generics <Args extends any[], Return>:
    • Args is a generic type representing the array of parameters the input function accepts. extends any[] ensures it's always a valid parameter list.
    • Return is a generic type representing the return value of the input function.
  • Input Function Type: fn: (...args: Args) => Return defines that the input fn is a function taking Args as parameters and returning Return.
  • Returned Function Type: The function returned by once has the exact same parameter and return type as the input function—this ensures type consistency when you call the wrapped function.
  • Internal Result Type: result is typed as Return | null to account for its initial null value. Once haveResult is true, we can safely use as Return to assert it's no longer null.

Example Usage

Here are a couple of examples to show how the type system works with this implementation:

// Example 1: Function with no parameters
const greetOnce = once(() => {
  console.log("Hello once!");
  return "greeting complete";
});

greetOnce(); // Logs "Hello once!", returns "greeting complete"
greetOnce(); // Returns "greeting complete" without logging

// Example 2: Function with typed parameters
const multiplyOnce = once((a: number, b: number) => a * b);
console.log(multiplyOnce(3, 4)); // 12
console.log(multiplyOnce(5, 6)); // Still 12 (first result is cached)
// multiplyOnce("3", 4); // TypeScript error! Argument type doesn't match

This setup ensures TypeScript will catch any mismatched parameter types when calling the wrapped function, and correctly infers the return type based on your input function.

内容的提问来源于stack exchange,提问作者donzul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:18:40