将索引签名添加到打字稿中定义的函数的推荐方法是什么

What is the recommended way to add index signature to a function defined in typescript

假设我有一个函数 el,在打字稿中定义:

function el():string { .. }

我想在以后向 el 添加键时删除类型冲突(没有索引签名):

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

是否可以在不转换为 any 的情况下做到这一点?

到目前为止,我找到的最佳解决方案是定义一个单独的接口并在分配时对其进行转换:

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

然后:

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

是否可以完全避免转换?如,在定义函数时将其与接口相关联或在定义函数时指定索引签名?

您可以在创建函数时将其转换为接口:

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

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

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

在 TypeScript 2.2 之前,您必须使用括号表示法来定义属性才能使其正常工作:

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