从对象键动态创建类型

时间:2019-06-05 10:50:13

标签: typescript typescript-typings

我有一个正在动态创建的icon-Map.json。示例:

import phoebe
import numpy as np
import matplotlib
matplotlib.use("agg")
import matplotlib.pyplot as plt

"""
This script loads and phoebe1 file, prepares parameters and priors,
and submits a fitting job using MCMC.  See phoebe2_loadresults.py
to view the results.
"""

b = phoebe.Bundle()
b.lc_fromfile('fakedata.lc', columns=['time','flux'], dataref='fakedata')

# By default all datasets will be used for fitting.
# If you wanted, you could disable any by label:
#~ b.disable_lc('fakedata')

# Now we need to choose our parameters to fit and setup their priors.
# We'll use the same distribution as in the Phoebe1 example, but note
# that Phoebe2 also currently supports normal distributions

# inclination (87.9)
b.set_prior('incl', distribution='uniform', lower=80, upper=90)
b.set_adjust('incl')

# teff@primary (6543)
b.set_prior('teff@primary', distribution='uniform', lower=5000, upper=7000)
b.set_adjust('teff@primary')

# pot@primary (5.123)
b.set_prior('pot@primary', distribution='uniform', lower=4.0, upper=8.0)
b.set_adjust('pot@primary')

# For third light, we'll just allow the synthetics to scale and offset.
# These don't need priors, but do need to be set to be adjusted
b.set_adjust('offset@fakedata')
b.set_adjust('scale@fakedata')

b.run_fitting('lmfit', computelabel='preview', accept_feedback=True)

b.plot_obs('fakedata')
b.plot_syn('fakedata')

plt.savefig('lmfit_after.png')
  • 我无法从该对象手动创建接口,因为我正在动态创建它,因此无法使用keyof。

  • 最终,我想创建一种iconMap的键类型,我可以在组件外部使用它,它将仅将我的输入限制为iconMap的键。 (联合或枚举):

const iconMap = {
    angleDoubleRight: 'angleDoubleRight.svg',
    angleRight: 'angleRight.svg',
    assets: 'assets.svg',
    barChart: 'barChart.svg',
    cancel: 'cancel.svg',
    chevronDown: 'chevronDown.svg',
    dotChart: 'dotChart.svg',
    dotMenu: 'dotMenu.svg',
    horizontalDots: 'horizontalDots.svg'
    ...

};

1 个答案:

答案 0 :(得分:2)

在您的问题中,您说不能使用keyof,但我不确定为什么。如果您有一个在编译时就知道其键的对象(这意味着iconMap变量是在之前生成的,则编译使用该变量的TypeScript代码),可以使用typeof type query operator获取其类型,然后在其上使用keyof

const iconMap = {
  angleDoubleRight: "angleDoubleRight.svg",
  angleRight: "angleRight.svg",
  assets: "assets.svg",
  barChart: "barChart.svg",
  cancel: "cancel.svg",
  chevronDown: "chevronDown.svg",
  dotChart: "dotChart.svg",
  dotMenu: "dotMenu.svg",
  horizontalDots: "horizontalDots.svg"
  //...
};

type IconMapMember = keyof typeof iconMap;
// type IconMapMember = "angleDoubleRight" | "angleRight" | "assets" | "barChart" 
// | "cancel" | "chevronDown" | "dotChart" | "dotMenu" | "horizontalDots" ...

Link to code

如果您遇到某些导致该解决方案无法正常工作的问题,请使用有关构建过程的更多详细信息来更新您的问题。希望这可以帮助;祝你好运!