【问题标题】:Can a typescript function's return type be determined by parameters打字稿函数的返回类型可以由参数确定吗
【发布时间】:2021-07-29 03:13:40
【问题描述】:

我有一个函数,其中一个 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 ......"});

【问题讨论】:

    标签: typescript typescript-generics


    【解决方案1】:

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

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

    Playground Link

    【讨论】:

      猜你喜欢
      • 2022-01-12
      • 1970-01-01
      • 2015-08-10
      • 2021-10-04
      • 2019-07-16
      • 2020-05-09
      • 1970-01-01
      • 2021-09-17
      • 1970-01-01
      相关资源
      最近更新 更多