typescript - 打字稿函数的返回类型可以由参数确定吗
问题描述
我有一个函数,其中一个 args 是一个字符串数组。它返回一个对象,其中所有键都是该字符串数组中的值。是否可以使 Typescript 中的函数返回类型反映这一点?
我认为用一个例子可以更好地解释这一点:
const clientConfigs =
getClientConfigs(clientId, ['timeZone', 'flagRequireTwoApprovals']);
// Above function will return a value for each requested configuration.
// This will look something like:
// {
// "timeZone": "America/New_York",
// "flagRequireTwoApprovals": true
// }
// At this point, the type of clientConfigs is: Record<string, any>
// HOWEVER, I want the type to be:
// Record<'timeZone'|'flagRequireTwoApprovals', any>
// I want this to be identified as error, because I
// forgot to capitalize "Z" in "timeZone":
const clientTime = moment.tz(clientConfigs.timezone).toISOString();
// I want this to be identified as error, because I
// forgot to retrieve the "adminEmail" config:
await sendEmail({to: configs.adminEmail, body: "Failed to whatever ......"});
解决方案
是的,只需为属性名称创建一个类型参数:
function test<K extends string>(keys: K[]): Record<K, any> {
const r: Record<K, any> = Object.create(null);
keys.forEach(k => r[k] = 'foobar');
return r;
}
用法:
// obj: Record<'foo' | 'bar' | 'baz', any>
const obj = test(['foo', 'bar', 'baz']);
推荐阅读
- python - 熊猫:groupby 操作后如何取回原始索引
- javascript - 页面刷新后保持滚动位置并保存切换
- c++ - 在 C++ 中初始化变量
- c# - 从同步函数调用异步函数
- javascript - 如何在wordpress的if/else条件下使用PHP/Javascript隐藏类?
- r - 使用 nflscrapR 抓取 2019 年数据时出错。刚开始收到
- python-3.x - 在 BeautifulSoup / Python 中,如何从结果集中提取单个元素?
- laravel - 419 抱歉,您的会话已过期。请刷新并重试。提交表单时出现此错误
- r - 错误:尝试在 For 循环中使用零长度变量名
- sql - 基于最小值分组时选择一条记录