Typescript如何使用映射类型创建嵌套的接口对象?

时间:2018-09-03 14:25:32

标签: javascript typescript typescript-typings

我想要的数据如下

paymentProviderByCountry = {
    England: worldPay,
    Spain: worldPay
}

如何为paymentProviderByCountryObj创建以所需的动态格式集成paymentProvidersListcountryList的接口。

我想我正在寻找的是如何递归地创建obj

    enum paymentProvidersList {
    WorldPay,
    Paypal,
}
enum countryListEnum {
    England,
    France,
    Spain,
}

type T0 = { [key in paymentProvidersList]: string }; // This would work

/*
  I want the values on paymentProviderByCountryObj to be dynamic based on the
   enum values so that i can have an object that looks like this

  paymentProviderByCountry = {
    England: WorldPay,
    Spain: Paypal,
    France: WorldPay
}
*/
interface paymentProviderByCountryObj {
    // This is the complex case, i cant get the index of the class to be dynamic and also its value
    [key in countryListEnum] :string : { [key in paymentProvidersList]: string }; 
}

export interface sysConfigInterface {
    paymentProviders: paymentProvidersList,
    paymentProviderByCountry: paymentProviderByCountryObj,
    minPaymentThreshold: String,
}

The Example Link

2 个答案:

答案 0 :(得分:0)

您正在寻找in(作为here的一部分在TypeScript 2.1中引入)

{ [key in countryList]: paymentProvidersList }

或者,如果您不想通过每个国家/地区:

{ [key in countryList]?: paymentProvidersList }

答案 1 :(得分:0)

这最终实现了我的最终目标

enum paymentProvidersList {
        WorldPay,
        Paypal,
    }
    enum countryListEnum {
        England,
        France,
        Spain,
    }

    // Or Record<countryListEnum, paymentProvidersList>
    type paymentProviderByCountryObj = { [k in countryListEnum]: paymentProvidersList } 

    const paymentProviderByCountry: paymentProviderByCountryObj = {
        [countryListEnum.England]: paymentProvidersList.WorldPay,
        [countryListEnum.France]: paymentProvidersList.WorldPay,
        [countryListEnum.Spain]: paymentProvidersList.Paypal
    }