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

Flow typed don't statically type object property types

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

这是流量限制还是有办法处理?

这是展示我想要实现的目标的示例代码

/* @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

我在 github 流程回购 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