0
votes

Let us say I have a function el, defined in typescript:

function el():string { .. }

I would like to remove the type violation (has no index signature) when later adding keys to el:

el.x = () => {...}

Is this possible to do without casting to any ?

So far the best solution I have found is to define a separate interface and casting to it while assigning:

interface ElFactory {
  [index: string]: () => string
  (): string
}

And then:

(el as ElFactory).x = () => {}

Is it possible to avoid the casting entirely ? As in, while defining the function associate it with the interface or specify the index signature while defining the function ?

1
It is not really clear what you are looking for. Could you provide some example? For me currently it looks like you want to extend a Function type?smnbbrv
I want a variable el which can be invoked as a function el() and which has function members el.x().lorefnon

1 Answers

1
votes

You can cast your function to the interface when it is created:

interface ElFactory {
  [index: string]: () => string
  (): string
}

var el = function (): string {
    return "test";
} as ElFactory;

el.test1 = () => "22"; // works
el.test2 = "22"; // error

Prior to TypeScript 2.2 you will have to use the bracket notation to define properties for this to work:

el["test1"] = () => "22"; // works
el["test2"] = "22"; // error