Reputation: 593
my example pretty much explains the issue.
but basically, I'm trying to understand how to write valid typescript when adding static members to a function in the code below
export const ZoomPanelControl = (props) => undefined;
ZoomPanelControl.Item = (props) => undefined;
Upvotes: 0
Views: 55
Reputation: 250872
If you need "a gap" between defining the function and assigning the properties, you can use a type assertion:
type Example = {
(props: any): any;
[key: string]: (props: any) => any;
}
const ZoomPanelControl = <Example>((props) => undefined);
//...
ZoomPanelControl.Item = (props) => undefined;
You could place the type within the type assertion, but that's one heck of a line of code to read, which is why I pulled it out into the Example
type instead.
The compiler still makes a general check of ((props) => undefined)
against the the signature of the Example
type - so there is type safety in there as opposed to one common alternative:
const ZoomPanelControl: Example = <any>((props) => undefined);
And you can limit it to known members, if you don't want to allow "any string as a key"...
type Example = {
(props: any): any;
Item: (props: any) => any;
}
If you are setting this up in one hit, jcalz answer has the benefit of type-inference (it effectively gives you the type in my last code block, but for free).
Upvotes: 0
Reputation: 327819
The most straightforward way to add a property to a function is to use Object.assign()
to create the function-with-property in a single statement:
export const ZoomPanelControl = Object.assign(
(props) => undefined,
{ Item: (props) => undefined }
);
This produces an object of type ((props: any) => any) & { Item: (props: any) => any; }
, which is what you want:
ZoomPanelControl(123); // okay
ZoomPanelControl.Item(456); // okay
Good luck!
Upvotes: 1