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



我想创建一种类型的国家-地区地图,以避免在选择国家及其相应地区时出错。

我也不想把所有绘制地图的国家和地区都包括在内,只想把那些相关的国家和区域包括在内。根类型(国家(的密钥可能存在也可能不存在(因为程序员可以只选择列出的国家中的一个(,但每个密钥(如果存在(都有一个带有强制值的映射类型;一旦你选择了一个根密钥,你就被提交,直到最终选择。

这是我的尝试:

国家.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';

函数.ts

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

某些测试特定

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

不幸的是,这让我进入了测试案例中的每个国家,即根类型的意大利和西班牙。

想明白了!

根类型需要围绕其类型设置OR逻辑。

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

相关内容

最新更新