如何为bind函数添加类型定义?jshue类型定义调用报错求助
Hey there! Let's break down why you're hitting this error and how to fix it without declaring extra variables.
The Root Issue
Your current IHue interface only defines the discover and bridge methods, but the actual jsHue value is a callable function (since it's the result of jsHueAPI.bind()). TypeScript doesn't recognize it can be invoked because your interface lacks a call signature.
The Solution: Add a Call Signature to the Interface
TypeScript lets interfaces describe both functions and their associated properties. We just need to extend your IHue interface to include a call signature that matches how jsHue is actually used.
Here's the updated type definition:
declare module 'jshue' { export interface IHue { // Add the call signature matching how you invoke jsHue() // Adjust the return type if calling jsHue() returns a different object (): IHue; discover: () => Promise<Array<any>>; bridge: (ip: string) => any; } var jsHue: IHue = jsHueAPI.bind(null, fetch, Response, JSON, Promise); export default jsHue; }
Why This Works
By adding (): IHue to the interface, you're telling TypeScript two key things:
jsHueis a function that can be called with no arguments- Calling it returns an object that matches the
IHueinterface (complete withdiscoverandbridgemethods)
If calling jsHue() actually expects parameters or returns a different type, just adjust the call signature to match jshue's real behavior (e.g., (config: HueConfig): IHue if it takes a config object).
Testing It Out
With this change, calling jsHue() should no longer throw the "not callable" error, and you'll keep proper type hints for discover and bridge on the returned object—all without needing to declare extra variables.
内容的提问来源于stack exchange,提问作者Firman Jamal

