TypeScript:如何从函数定义推导接口?
Absolutely, you can pull this off in TypeScript! The key thing to note is that when referencing a function in an interface, you need to use its type (not the function value itself). Let me walk you through a couple of clean ways to make this work correctly:
Method 1: Define a function type alias first
This approach explicitly separates the function's signature from its implementation, making the type easy to reuse elsewhere:
// Step 1: Create a type alias for your function's signature type MyFunctionType = (arg1: string, arg2: number) => boolean; // Step 2: Implement the function using the type alias const myFunction: MyFunctionType = (arg1, arg2) => { // Replace this with your custom logic return arg2 > arg1.length; }; // Step 3: Build your interface using the type alias interface MyInterface { someOtherProperty: string; myFunction: MyFunctionType; // Matches the exact signature you need }
Method 2: Use typeof to reference an existing function's type
If you already have the function defined, you can skip the type alias and use typeof to grab its signature directly:
// Step 1: Define your function first function myFunction(arg1: string, arg2: number): boolean { // Your custom logic here return arg2 > arg1.length; } // Step 2: Reference the function's type in the interface with typeof interface MyInterface { someOtherProperty: string; myFunction: typeof myFunction; // Inherits the exact signature from myFunction }
Why your original approach doesn't work
When you wrote myFunction: myFunction in the interface, TypeScript throws an error because the right-hand myFunction is a value (the actual function), not a type. Using typeof myFunction tells TypeScript to use the function's signature type instead of the value itself.
Example of using the interface
Once everything is set up, you can create objects that conform to MyInterface like this:
const myObject: MyInterface = { someOtherProperty: "TypeScript is great!", myFunction: myFunction }; // Test the function console.log(myObject.myFunction("hello", 6)); // Logs true (since "hello" has length 5, 6 > 5)
内容的提问来源于stack exchange,提问作者Michael.Lumley

