首页 > 解决方案 > 打字稿 - 使用函数字典

问题描述

我正在尝试创建一个函数字典,如下所示:

type Test = {
  first: (args: { a: string }) => void;
  second: (args: { b: number }) => void;
};

const library: Test = {
  first: (args: { a: string}) => console.log(args),
  second: (args: { b: number}) => console.log(args),
};

const choice = <K extends keyof Test>(
  page: K, options: Parameters<Test[K]>[0],
) => library[page](options); // typescript complains here by underlining 'options' with error:
// Property 'a' is missing in type '{ b: number; }' but required in type '{ a: string; }'

// Later we use choice
choice('first', { a: 'test' }); // however here it is enforced that the args can only 
// be 'a' for 'first' and 'b' for 'second' as I would expect and is the desired outcome

为了加深我的理解,我想知道为什么会发生这种情况,以及是否有正确的方法来询问TS。

标签: typescript

解决方案


推荐阅读