代码之家  ›  专栏  ›  技术社区  ›  Noitidart

不允许多个索引器出错,但它们不是索引器

  •  0
  • Noitidart  · 技术社区  · 8 年前

    我的目标是创建一个 Entities 类型,它是中所有键的“精确对象类型” K .

    K 是:

    type SocialEntity =     Article    | Thumb    | Comment    | Displayname    | Helpful;
    type SocialEntityKind = 'articles' | 'thumbs' | 'comments' | 'displaynames' | 'helpfuls';
    
    
    const K:  {[key: SocialEntityKind]: SocialEntityKind} = { // short for SOCIAL_ENTITY_KIND
        articles: 'articles',
        thumbs: 'thumbs',
        comments: 'comments',
        displaynames: 'displaynames',
        helpfuls: 'helpfuls'
    }
    

    现在我试着设置 [key: typeof K.*] 但它考虑了这些索引。

    type Entities = {|
        [key: typeof K.articles]: {
            [key: ArticleId]: Article
        },
        [key: typeof K.thumbs]: {
            [key: ThumbId]: Thumb
        },
        [key: typeof K.comments]: {
            [key: CommentId]: Comment
        },
        [key: typeof K.displaynames]: {
            [key: DisplaynameId]: Displayname
        },
        [key: typeof K.helpfuls]: {
            [key: HelpfulId]: Helpful
        }
    |}
    

    以下是错误的屏幕截图:

    有什么简单而正确的方法可以做到这一点吗?

    1 回复  |  直到 8 年前
        1
  •  1
  •   loganfsmyth    8 年前

    这种语法对您要做的事情不起作用。 [key: TYPE]: TYPE 在Flowtype中,语法是 using objects as dictionaries ,而不是计算属性名称的语法。

    也不可能使用 typeof 以你想要的方式,因为类型只是 string articles 确切地你必须手动输入钥匙的名称。