I want to create an interface for an object that has optional properties with specific names, but also accepts arbitrarily named properties. This is what I tried.
interface CallBack {
onTransition?(): any; // can have this
[key: string]: () => any; // or this. But not both
}
But received this error:
Property 'onBeforeTransition' of type '(() => any) | undefined' is not assignable to string index type '() => any'.
I recognize that this will semantically mean the same thing as:
interface CallBack {
[key: string]: () => any;
}
The reason I want this functionality is in order to have editor help when defining callbacks. Is there any way to achieve this?
You can make the return type of the index signature return (() => any) | undefined. This might be a good idea anyway, as any string access to the object will probably return a function or undefined and should be checked anyway.
interface CallBack {
onTransition?(): any;
[key: string]: (() => any) | undefined;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With