我正在尝试为我们使用的字典创建一个类型。我们所做的有点奇怪,但我会尽力解释。我们在应用程序中有一个字典,声明如下:
  localisation: LocalDico = {
    page: ['Page', 'Page'],
    of: ['of', 'de'],
    items: ['items', 'items'],
    itemsPerPage: ['items per page', 'items par page']
  };其中索引0是英语,索引1是法语。
LocalDico类型如下:
interface LocalDico {
  page: [string, string] | string;
  of: [string, string] | string;
  items: [string, string] | string;
  itemsPerPage: [string, string] | string;
}这背后的原因是,在我们的代码中,我们不希望总是像这样
this.localDico.page[this.language]因此,我们继续将其转换为如下所示的对象
//Obviously this is done programatically we dont actually recode everything
localDico: LocalDico = {
  page: 'Page', 
  of: 'Of', 
  items: 'Items', 
  itemsPerPage: 'Items per page'
}我的目标是,如果有人创建本地化(使用多种语言的本地化),试图只放置一个字符串,它会引发错误。但是使用localDico的人使用它作为字符串应该不会有任何问题。
基本上我想
interface LocalDico {
  page: string, 
  of: string, 
  items: string, 
  itemsperPage: string
}
and 
interface Localisation{
  page: [string, string],
  of: [string, string],
  items: [string, string],
  itemsperPage: [string, string]
}显然,这是一本简单的字典,我们有一些包含数百个条目的字典。我不想总是重复接口,我宁愿有一个接口定义所有可能的键,而另一个接口基本上说明这个变量的每个键都是一个字符串或包含2个字符串的数组。
很抱歉,这篇很长的帖子只是想要彻底和清晰,尽管我不确定它是不是。如果不清楚,请让我知道
谢谢!
发布于 2019-03-28 22:54:25
当然,您可以使用映射类型,如下所示:
interface LocalDico {
  page: string, 
  of: string, 
  items: string, 
  itemsperPage: string
}
type Localisation = { [key in keyof LocalDico]: [string, string] };或者更干净一点(在我看来):
// NOTE: an enum would also work here
type LocaleKeys = 
  | 'page'
  | 'of'
  | 'items'
  | 'itemsperPage'
type LocalDico = { [key in LocaleKeys]: string }
type Localisation = { [key in LocaleKeys]: [string, string] }https://stackoverflow.com/questions/55400522
复制相似问题