You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何定义返回与ContentMap键关联的Map对象Promise的函数类型

实现符合期望的getContent类型定义

要让getContent根据输入的ContentMap键数组,返回包含对应键值类型的对象的Promise,你需要调整泛型和返回类型的逻辑,将输入数组中的键映射为目标对象的键值对,具体实现如下:

type ContentMap = {
  one: number,
  two: string,
  three: { name: string }
}

const getContent = <T extends readonly (keyof ContentMap)[]>(inputs: T): Promise<Pick<ContentMap, T[number]>> => {
  // 示例异步实现逻辑
  return Promise.resolve(inputs.reduce((result, key) => {
    result[key] = /* 实际获取对应内容的逻辑 */ {} as ContentMap[typeof key];
    return result;
  }, {} as Pick<ContentMap, T[number]>));
};

关键调整说明

  1. 泛型约束:将泛型T的约束改为readonly (keyof ContentMap)[],适配字面量数组被TypeScript自动推断为只读数组的场景,和Promise.all的泛型约束风格保持一致。
  2. 返回类型:使用Pick<ContentMap, T[number]>构造目标类型:
    • T[number]提取数组T中所有元素的联合类型(比如输入['one','two']时,T[number]为'one' | 'two')
    • Pick<ContentMap, ...>从ContentMap中挑选出指定键对应的键值对类型,完全匹配期望的返回结构。

验证效果

当调用getContent(['one', 'two'])时,TypeScript会正确推断返回类型为Promise<{ one: number; two: string; }>,与你给出的期望效果完全一致。

内容的提问来源于stack exchange,提问作者Aliunco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 15:53:14