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>:Argsis a generic type representing the array of parameters the input function accepts.extends any[]ensures it's always a valid parameter list.Returnis a generic type representing the return value of the input function.
- Input Function Type:
fn: (...args: Args) => Returndefines that the inputfnis a function takingArgsas parameters and returningReturn. - Returned Function Type: The function returned by
oncehas the exact same parameter and return type as the input function—this ensures type consistency when you call the wrapped function. - Internal Result Type:
resultis typed asReturn | nullto account for its initialnullvalue. OncehaveResultistrue, we can safely useas Returnto assert it's no longernull.
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
相关产品推荐
相关产品推荐

