typescript - 打字稿 - 使用函数字典
问题描述
我正在尝试创建一个函数字典,如下所示:
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。
解决方案
推荐阅读
- regex - 交替与布尔或有何不同?
- angular - 两个垂直和水平选项卡 - 不工作垫选项卡
- ios - 没有从开发 pod 安装并从主项目构建的此类模块“Podname”
- swiftui - SwiftUI:在 Firebase ML Kit 识别的元素周围绘制矩形
- python - Python 3.8.1 - PermissionError: [Errno 13] Permission denied
- c# - 如何在统一上修复此错误:无法将浮点类型隐式转换为 UnityEngine.transform
- python - 似乎无法让 Boto 的 dynamodb.update_item 工作
- javascript - React Navigation V5 隐藏底部选项卡
- node.js - 我应该如何对需要续集的东西进行单元测试?
- bash - Bash - 如何在后台进程描述中显示变量值而不是名称?