Javascript 如何在流中使用(或模拟)具有覆盖字段的对象扩展?

Javascript 如何在流中使用(或模拟)具有覆盖字段的对象扩展?,javascript,typescript,flowtype,Javascript,Typescript,Flowtype,这不会在“Try Flow”上编译: 错误是: const y: B = { ...x, a: x.a.toString() } ^ Cannot assign object literal to `y` because number [1] is incompatible with string [2] in property `a`. References: 3: type A = { a: number, b: string};

这不会在“Try Flow”上编译:

错误是:

const y: B = { ...x, a: x.a.toString() }
                ^ Cannot assign object literal to `y` because number [1] is incompatible with string [2] in property `a`.

    References:

    3: type A = { a: number, b: string};
                     ^ [1]

    4: type B = { a: string, b: string };
                     ^ [2]
请注意,这段代码在TypeScript中工作(当我删除字段重写时,它无法按照预期进行编译)


如何在不枚举原始对象的所有字段的情况下在流中实现相同的行为?简短回答:你不能这样做,这是一个“已知”的问题。它是“已知”的,但我没有看到任何迹象表明有人正在研究它

你可以:

  • 声明
    B.a
    number | string
    的并集
  • 声明如下所示的映射函数:

    const mapfn = ({ a, ...rest }: A): B => ({ ...rest, a: a.toString() });
    
    const x: A = { a: 1, b: '2' };
    const y: B = mapfn(x);
    

编辑:看来你现在可以用最新版本的Flow来做这件事了。有关详细信息,请参阅上面的问题,他们已修复此错误。升级你的流量

计划于下周发布的Flow v0.111.0中对排列进行了一些重大改进。这段代码现在将进行类型检查。通过切换到“主”版本,您可以在中看到它正在运行

const mapfn = ({ a, ...rest }: A): B => ({ ...rest, a: a.toString() });

const x: A = { a: 1, b: '2' };
const y: B = mapfn(x);