如何将普通对象的类型定义为函数参数

时间:2020-06-14 05:45:25

标签: typescript

我写了一些下面的代码。由于函数参数是一个普通对象,因此我使用索引类型对其进行了键入。但是ts报告错误Property 'text' is missing in type 'ICommandOptions' but required in type '{ text: string; }'。我以为{ text: string; }{ [key: string]: any; }匹配,但实际上没有。我不想通过使用联合类型或其他东西来定义特定的键。有什么好主意吗?

type ICommandOptions = {
  [key: string]: any;
};

type ICommandMap = {
  [key: string]: (options: ICommandOptions) => any;
};

function commandA(options: { text: string }) {}

function commandB(options: { count: number }) {}

function commandC(options: { enabled: boolean }) {}

const commandMap: ICommandMap = {
  commandA, commandB, commandC // <-- ts reports errors
};

0 个答案:

没有答案