【问题标题】:How to create type with constants properly with Flow in Javascript?如何使用 Javascript 中的 Flow 正确创建带有常量的类型?
【发布时间】:2023-03-18 14:05:01
【问题描述】:

我正在使用 Flow 为 React 应用程序创建类型。我不确定如何正确执行此操作。

我想为以后可以访问的类型中的可能条目(作为枚举)设置常量,并且我希望该类型包含常量而不是文字。

// @flow

export const CARD_TYPE = {
 firstType: 'one',
 secondType: 'two',
};

export type CardType = {
 type: CARD_TYPE,
};

我希望我能够在我的组件中使用 CARD_TYPE 作为常量,并将 CardType 作为类型,但是我收到以下错误:

流程:不能使用对象字面量作为类型,因为对象字面量是一个值。要获取值的类型,请使用typeof

【问题讨论】:

    标签: javascript types flowtype


    【解决方案1】:

    希望我能正确理解您的问题。您应该能够执行以下操作

    // @flow
    
    export const CARD_TYPE = {
     firstType: 'one',
     secondType: 'two',
    };
    
    
    export type CardType = $Keys<typeof CARD_TYPE>
    

    这是codepen of the solution with no errors

    【讨论】:

      猜你喜欢
      • 2019-03-12
      • 1970-01-01
      • 2019-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-12
      相关资源
      最近更新 更多