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

流类型化不静态类型对象属性类型

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

    我有一个对象,它包含静态类型的不同属性。问题是,当我尝试静态访问其中一个属性时,flow似乎无法理解并返回我要访问的特定属性的类型。

    这是流量限制还是有办法解决?

    下面是一个示例代码,展示了我想要实现的目标

    /* @flow */
    const object = (({
      first: 'first',
      second: 2,
    }): {
      first: string,
      second: number
    });
    
    type ObjectPropertiesType = $Keys<typeof object>;
    
    const getObjectValue = (property: ObjectPropertiesType) => {
      if (!object[property]) throw new Error(`object.${property} not exisiting`);
    
      return object[property];
    };
    
    // -> Flow here complains that getObjectValue isn't compatible with string but is string | number
    const getFirst = (): string => getObjectValue('first');
    

    See it in action in flow type repl

    1 回复  |  直到 8 年前
        1
  •  0
  •   BentoumiTech    8 年前

    我在github flow repo上回答了这个问题 https://github.com/flowtype/flow-bin/issues/112

    以下是解决方案:

    /* @flow */
    const object = (({
      first: 'first',
      second: 2,
    }): {
      first: string,
      second: number
    });
    
    type ObjectPropertiesType = $Keys<typeof object>;
    
    type GetValueType = <Prop: string>(property: Prop) => $ElementType<typeof object, Prop>;
    
    const getObjectValue: GetValueType = (property) => {
      return object[property];
    };
    
    const getFirst = (): string => getObjectValue('first');
    const getSecond = (): number => getObjectValue('second');
    const getSecondWrong = (): string => getObjectValue('second');
    const getWrong = (): string => getObjectValue('third');
    

    See it in action