如何处理打字稿中的常量?

时间:2019-01-28 08:06:37

标签: javascript reactjs typescript types

我有一个类似的反应组件:

const myComponent = ({constant}: Iprops) => (
  <div>
    {CONSTANTS[constant].property ? <showThis /> : null
  </div>
)

它抱怨element implicitly has an 'any' type because type 'object' has no index signature

如何将CONSTANTS添加到我的界面?我尝试过

interface IProps {
    [CONSTANTS: any]: {
        constant: boolean;
    }
}

但显然不是那样。如何声明对象中每个键的类型?

谢谢

1 个答案:

答案 0 :(得分:1)

我不确定我是否了解您实际需要的对象的形状。但是您可以使用以下语法键入对象:

const CONSTANTS: { [key:string]: boolean } = {}
CONSTANTS["something1"] = false; // ok
CONSTANTS["something2"] = "Hey"; // not ok

这有点棘手,因为键实际上可以be either string or number,但是值类型已正确实施,因此您在那里仍然可以使用更复杂的类型,而不是boolean

相关问题