如何描述始终返回预定义值类型的代理对象类型?

时间:2018-05-24 12:19:38

标签: javascript flowtype

我目前有以下辅助函数来创建一个总是返回结果或抛出错误的getter函数:

// @flow

type StrictMapType<V> = {
  [key: string]: V
};

const createStrictMap = <V: *>(map: StrictMapType<V>): (name: string) => V => {
  return (name) => {
    if (name in map) {
      return map[name];
    }

    throw new Error();
  };
};

const persons = createStrictMap({
  bar: 'BAR',
  foo: 'FOO'
});

const foo: string = persons('foo');

// This triggers Flow error.
const bar: number = persons('bar');

但是,我想使用代理对象抽象相同的逻辑,例如

// @flow

type StrictMapType<V> = {
  [key: string]: V
};

const createStrictMap = <V: *>(map: StrictMapType<V>) => {
  return new Proxy(
    map,
    {
      get: (subject, name) => {
        if (name in subject) {
          return subject[name];
        }

        throw new Error();
      }
    }
  );
};

const persons = createStrictMap({
  bar: 'BAR',
  foo: 'FOO'
});

const foo: string = persons.foo;

// This triggers Flow error.
const bar: number = persons.bar;

如何描述始终返回预定义值类型的代理对象类型?

1 个答案:

答案 0 :(得分:0)

您可以将返回类型定义为输入类型+索引器属性:

type StrictMap<T> = T & { [key: string]: any };

function createStrictMap<T: *>(map: T): StrictMap<T> {
  return new Proxy(
    map,
    {
      get: (subject, name) => {
        if (name in subject) {
          return subject[name];
        }

        throw new Error();
      }
    }
  );
};

const persons = createStrictMap({
  bar: 1,
  foo: 'FOO'
});

const foo: string = persons.foo;
const bar: number = persons.bar;
const another: number = persons.another;