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

TypeScript中能否根据数组对象的key获取对应fallback类型?

问题

我定义了如下带有const断言的对象数组:

const features = [{ key: 'some-key', fallback: true }, { key: 'another-key', fallback: 'a string' }] as const;

可见每个对象的fallback值类型不同。我希望编写一个getFeature函数,用于从API获取特性值,若无结果则返回fallback,同时支持传入自定义fallback参数,要求该参数的类型需与传入的key对应的原数组中fallback的类型匹配。例如调用getFeature('some-key', [...])时,fallback参数必须是boolean类型;调用getFeature('another-key', [...])时,必须是string类型。目前我已通过type FeatureKey = typeof features[number]['key'];获取了所有可能的key类型,请问能否实现根据传入的key自动推导fallback参数的类型?

解答

完全可以实现,核心是通过TypeScript的映射类型和泛型,让函数根据传入的key自动绑定对应的fallback类型。

1. 构建键与fallback类型的映射

先从features数组中提取每个key对应的fallback类型,生成一个映射关系:

type FeatureFallbackMap = {
  [F in typeof features[number] as F['key']]: F['fallback']
};

这个类型会自动生成如下结构:

type FeatureFallbackMap = {
  'some-key': boolean;
  'another-key': string;
}

2. 编写带泛型的getFeature函数

利用上面的映射类型,定义泛型函数,让泛型参数绑定到具体的key上,从而自动推导fallback的类型:

async function getFeature<K extends keyof FeatureFallbackMap>(
  key: K,
  customFallback?: FeatureFallbackMap[K]
): Promise<FeatureFallbackMap[K]> {
  // 模拟API请求逻辑
  const apiResponse = await fetch(`/api/features/${key}`);
  const data = await apiResponse.json();

  // 优先返回API结果,无结果则用自定义fallback或原数组默认值
  if (data.value !== undefined) {
    return data.value as FeatureFallbackMap[K];
  }
  if (customFallback !== undefined) {
    return customFallback;
  }
  return features.find(f => f.key === key)!.fallback;
}

3. 类型校验效果

调用函数时,TypeScript会自动根据传入的key校验fallback类型:

// ✅ 合法:customFallback为boolean类型
getFeature('some-key', false);

// ❌ 报错:customFallback应为string类型,这里传了boolean
getFeature('another-key', true);

// ✅ 合法:不传customFallback时,返回值类型自动匹配对应key的fallback类型
const someFeature = await getFeature('some-key'); // someFeature类型为boolean
const anotherFeature = await getFeature('another-key'); // anotherFeature类型为string

内容的提问来源于stack exchange,提问作者R. Groot Jebbink

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 08:23:12