首页 > 解决方案 > 将索引签名添加到 .d.ts 中的函数

问题描述

我想覆盖 npm 库类型以向函数添加索引签名。假设该函数没有做任何壮观的事情:

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

它有一个输入.d.ts文件:

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

我想为这个函数添加属性,比如:

foo['something'] = 2;

如何更改.d.ts文件,以便我不仅可以使用任何属性执行此操作something吗?它的索引签名应该是[index: string]: number;. 我已经找到了如何做到这一点的答案,但仅限于单个或几个已知属性,但我需要将任何字符串作为键。

标签: typescriptfunction-object.d.tsindex-signature

解决方案


我通过Object.assign在 TSPlayground 上使用将函数与对象(使用索引签名键入)合并找到了答案,它可以.d.ts为我生成:

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

export default parse;

推荐阅读