打字稿函数的返回类型可以由参数确定吗 [英] Can a typescript function's return type be determined by parameters

查看:30
本文介绍了打字稿函数的返回类型可以由参数确定吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,其中一个参数是一个字符串数组.它返回一个对象,其中所有键都是该字符串数组中的值.是否可以使 Typescript 中函数的返回类型反映这一点?

I have a function where one of the args is an array of strings. It returns an object where all of the keys are the values from that array of strings. Is it possible to make the function's return type in Typescript reflect this?

我认为用一个例子更好地解释这一点:

I think this is better explained with an example:

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 ......"});

推荐答案

是的,只需为属性名称设置一个类型参数:

Yes, just make a type parameter for the property names:

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']);

游乐场链接

这篇关于打字稿函数的返回类型可以由参数确定吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆