如何使用与 Typescript 中的国家/地区类型配对的可选键定义国家/地区类型?

How do I Define a Countries Type with optional keys paired to types of countries in Typescript?

提问人:Owen Carter 提问时间:8/9/2022 更新时间:8/9/2022 访问量:78

问:

我想创建一种类型的国家/地区地图,以避免在选择国家/地区及其各自区域时犯错误。

我也不想包括曾经绘制过的每个国家和地区,只包括相关的国家和地区。其中根类型(国家/地区)的键可能存在也可能不存在(因为程序员可能只选择列出的国家/地区之一),但每个键(如果存在)都有一个具有强制值的映射类型;选择根密钥后,您将提交,直到最终选择。

这是我的尝试:

countries.ts

type Countries = {
  france?: France
  italy?: Italy
  spain?: Spain
}

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

functions.ts

export function selectCountryAndRegion(country: Country, region: Countries = {}): void {
  // do something special with countries
}

some-test.spec.ts

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

不幸的是,它让我在测试用例中输入每个国家,即根类型的意大利和西班牙。

节点 .js 打字稿 类型 嵌套类型

评论


答:

0赞 Owen Carter 8/9/2022 #1

想通了!

根类型需要围绕其类型具有 OR 逻辑。

type Countries = {
  france?: France | undefined
  italy?: Italy | undefined
  spain?: Spain | undefined
}