代码之家  ›  专栏  ›  技术社区  ›  Alex Wayne

流类型返回类型的函数,可以重写某些属性

  •  1
  • Alex Wayne  · 技术社区  · 6 年前

    $Shape<T> 好像在做我想做的,因为 "Copies the shape of the type supplied, but marks every field optional."

    但是,当我传播 $Shape<A> 在类型为的有效对象中 A

    // @flow
    
    type A = {
      a: number,
      b: ?string,
    }
    
    function foo(attrs: $Shape<A>): A {
      return {
        a: 123,
        b: 'asd', // <- string incompatible with null
        ...attrs, 
      }
    }
    
    foo({ b: 'foo' })
    

    Try flow link

    但是如果我把 ...attrs 错误消失。如果我通过 b: string ,错误也会消失。

    我错过了什么?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Steven Stark    6 年前

    你只需要 ? 在错误的一边 :

    type A = {
      a: number,
      b?: string,
    }
    

    编辑:

    经过讨论,问题似乎是在param中定义$Shape类型。

    幸运的是,我在外面设置了它,还为类型添加了一个索引器:

    // @flow
    
    type A = {
      [key: string]: string|number|null,
      a: number,
      b: string,
    }
    type ADetails = $Shape<A>;
    
    function foo(attrs: ADetails): A {
      return {
        ...attrs,
      }
    }
    
    foo({ b: 'foo' })