Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript interface for objects with some known but optional property names and some unknown property names

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?

like image 520
Hastradamus Avatar asked Oct 24 '25 01:10

Hastradamus


1 Answers

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;
}
like image 158
Titian Cernicova-Dragomir Avatar answered Oct 26 '25 16:10

Titian Cernicova-Dragomir