【问题标题】:Use values of object as a type - $Values - similar to $Keys使用对象的值作为类型 - $Values - 类似于 $Keys
【发布时间】:2017-08-26 23:13:25
【问题描述】:

从流程文档中我们得到:

// @flow
const countries = {
  US: "United States",
  IT: "Italy",
  FR: "France"
};

type Country = $Keys<typeof countries>;

const italy: Country = 'IT';
const nope: Country = 'nope'; // 'nope' is not a Country

我想怎么做

type CountryValue = $Values<typeof countries>
const italy: CountryValue = 'Italy'; // yes

这可能吗?

【问题讨论】:

    标签: flowtype


    【解决方案1】:

    您可以使用$Values,尽管您还需要做更多的事情,因为目前countries 中的值只是被检测为任何string。如果你告诉 flow 只允许某些值,那么它会起作用:

    type FullNames = "United States" | "Italy";
    
    const countries: {[key: string]: FullNames} = {
      US: "United States",
      IT: "Italy"
    };
    
    
    const nope: $Values(typeof countries) = 'nope'; // 'nope' is not in the value type
    

    我猜这不是您想要的相当,因为它需要显式添加类型,但它是可行的。

    【讨论】:

    • 啊该死,谢谢,看来我必须定义 type FullNames 枚举,所以不妨使用它吧?
    • 是的,看起来它不会从对象文字的值推断枚举类型。哪种类型是有意义的,因为大多数类型都有对象文字,您不想将其限制为初始值。
    • 非常感谢您的帮助,我已经接受了这一点,因为至少它有效并传达了它应该是该对象中的值并确保该对象中的值来自给定的信息: )
    • 这个答案更接近我想要的:使用 Object.freeze 以便 Flow 知道值不会改变:stackoverflow.com/a/51166430/592125
    猜你喜欢
    • 1970-01-01
    • 2017-06-09
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    • 2013-07-26
    • 1970-01-01
    • 1970-01-01
    • 2012-05-29
    相关资源
    最近更新 更多