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

如何在TypeScript中定义带可选键的国家区域映射类型?

解决TypeScript国家区域映射的可选键约束问题

你现在的问题是:定义了国家区域的层级类型,但调用函数时被迫要填写所有国家的键,没法只保留选中的国家结构。下面是具体的解决步骤:

问题根源

  1. 函数selectCountryAndRegion的第二个参数直接用了Countries类型,没有和第一个参数的选中国家做关联,导致TypeScript没法识别你只需要传选中国家的结构;
  2. 没定义Country类型,测试里传入的'France'和类型里的键france大小写不匹配;
  3. 现有类型虽然允许国家键可选,但没有通过泛型约束参数的关联性。

解决方案

1. 完善基础类型

先补上Country类型,确保国家名称和类型键一致:

// countries.ts
type Countries = {
  france?: France
  italy?: Italy
  spain?: Spain
}

// 新增:绑定Countries的键作为可选国家
type Country = keyof Countries;

// 以下原有类型保持不变
type France = {
  mainRegions: {
    northanFrance?: NorthanFrance
    centralFrance?: CentralFrance
    southernFrance?: SouthernFrance
  }
}

type NorthanFrance = {
  subRegions: SubRegionsInNorthanFrance
}
type CentralFrance = {
  subRegions: SubRegionsInCentralFrance
}
type SouthernFrance = {
  subRegions: SubRegionsInSouthernFrance
}

type SubRegionsInNorthanFrance = 'Paris'|'Brittany'|'Normandy'|'Picardy';
type SubRegionsInCentralFrance = 'Dordogne'|'Jura & The Alps'|'Vendee'|'Loire';
type SubRegionsInSouthernFrance = 'Gironde & Charente-Maritime'
|'Landes & The Pyrenees'|'Languedoc & Roussillon'|'Ardeche & Auvergne'
|'Riviera & Provence'|'Corsica';

type Italy = {
  mainRegions?: {
    northanItaly?: NorthanItaly
    centralItaly?: CentralItaly
  }
}
type NorthanItaly = {
  subRegions: SubRegionsInNorthanItaly
}
type CentralItaly = {
  subRegions: SubRegionsInCentralItaly
}

type SubRegionsInNorthanItaly = 'Adriatic Coast & Venetian Riviera'|'Lake Garda';
type SubRegionsInCentralItaly = 'Tuscany & Elba'|'Lazio & Campania'|'Sardinia';

type Spain = {
  mainRegions: MainRegionsInSpain
}
type MainRegionsInSpain = 'Costa Brava, Costa Dorada & Costa Verde';

2. 修改函数参数的关联约束

用泛型把第一个参数的选中国家和第二个参数的结构绑定,确保第二个参数只能包含选中国家的键,不需要填其他国家:

// functions.ts
import type { Countries, Country } from './countries';

export function selectCountryAndRegion<T extends Country>(country: T, region: Pick<Countries, T>): void {
  // 这里写你的业务逻辑
}

3. 修正测试用例

把国家名称改成和类型键一致的小写,并且只传选中国家的结构:

// some-test.spec.ts
import { selectCountryAndRegion } from './functions';

it('should select one region from one country', function () {
  selectCountryAndRegion('france', {
    france: {
      mainRegions: {
        northanFrance: {
          subRegions: 'Brittany'
        }
      }
    }
  });
});

效果说明

修改后,TypeScript会自动做以下校验:

  • 只允许你传入选中国家的结构,不需要填其他国家的键;
  • 如果漏填选中国家的必填项(比如France的mainRegions),会直接报错;
  • 如果填了非选中国家的键(比如选france却同时传italy),也会报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 19:07:37