typescript - 在 Typescript 中按名称从字典中调用函数
问题描述
假设我有一个具有多个功能的接口:
// Copyright 2020 Google LLC.
// SPDX-License-Identifier: Apache-2.0
interface MyFunctions {
func1: () => string;
func2: () => number;
func3: (value: string) => string;
}
现在我想按名称获取这些函数:
// Copyright 2020 Google LLC.
// SPDX-License-Identifier: Apache-2.0
type FuncNames = keyof MyFunctions;
function getFunc<T extends FuncNames>(key: T): MyFunctions[T] {
return myFuncInstance[key]; // Imagine I have instance coming from somewhere.
}
这实际上完全是类型安全的:
// Copyright 2020 Google LLC.
// SPDX-License-Identifier: Apache-2.0
const a = getFunc('func1')(); // a - string;
const b = getFunc('func2')(); // b - number;
const c = getFunc('func3')('some'); // c - string;
现在我想再做一步并在助手中调用函数:
// Copyright 2020 Google LLC.
// SPDX-License-Identifier: Apache-2.0
function callFunc<T extends FuncNames>(
key: T,
...params: Parameters<MyFunctions[T]>): ReturnType<MyFunctions[T]> {
const func = getFunc(key);
return func(...params); // Type error here.
}
所以我希望这个工作,但不能存档。TypeScript 可以吗?
// Copyright 2020 Google LLC.
// SPDX-License-Identifier: Apache-2.0
const a = callFunc('func1'); // a - string;
const b = callFunc('func2'); // b - number;
const c = callFunc('func3', 'some'); // c - string;
顺便说一句,签名的callFunc
检查正确。因此编译器成功地检查了上一个示例中的调用,并强制参数callFunc
正确,但我无法在此帮助程序中进行实际调用。因此,如果我做的事情就像const func: any = getFunc(key);
外面的一切仍然是类型安全的,但any
总是使用是一个不好的迹象。
是否可以使callFunc
完全类型安全?
解决方案
推荐阅读
- php - WordPress仪表板显示为一些编码文本
- snowflake-cloud-data-platform - 具有多个存储过程的任务
- active-directory - 使用 Identity Connect 的 SAML 配置按钮配置 SSO 时出现问题
- android - React-Native Android 不支持所需的屏幕密度和尺寸
- react-native - 世博推送通知令牌未定义
- angular8 - 禁用特定页面的浏览器后退按钮(登录页面)
- html - 我试图添加必需的属性但不工作
- laravel - 使用 Laravel 检索 AWS cloudwatch 日志
- azure - 在使用 GZIP 编解码器的 csv.gz 文件的 Azure Synapse Analytics 中执行 COPY 语句时收到错误
- amazon-redshift - 使用 Boto3 设置 Redshift 集群可见性