typescriptfunction-object.d.tsindex-signature

Add index signature to a function in .d.ts


I want to overwrite npm library typing to add index signature to a function. Let's say the function does nothing spectacular:

export function foo(input) {
  return Number(input);
}

It has a typing in .d.ts file:

export default function foo(input: string): number | null;

I want to add properties to this function, like:

foo['something'] = 2;

How to change .d.ts file so it will allow me to do this with any property not only something? It should have index signature of [index: string]: number;. I have found answers how to do it, but only for a single or few known properties, but I need to put any string as a key.


Solution

  • I found the answer myself by merging function with object (typed with index signature) using Object.assign on TSPlayground and it can generate .d.ts for me:

    declare const foo: ((input: string) => number | null) & {
      [key: string]: number;
    };
    
    export default parse;