【问题标题】:Cannot assign object literal to `...` because property `...` is missing in object literal [1] but exists in `...`无法将对象文字分配给`...`,因为在对象文字[1]中缺少属性`...`但存在于`...`中
【发布时间】:2018-11-10 06:45:44
【问题描述】:

我是新流程,目前正在从事流程严格的项目。我有一个类型别名被传递给一个类。 sn-p 可以找到here

// @flow strict

export type CustomType = {
  a: string,
  b: boolean,
  c: boolean,
  d: boolean,
  e: boolean
};
let d = true;
let b = true;
let customType:CustomType = {
        d,
        b,
        c: true,
 }

class Custom{
  constructor(customType = {}) {}
}

let custom = new Custom(customType);

传递对象时,并非所有属性 customType 都存在。这里最好的解决方法是什么?

【问题讨论】:

    标签: flowtype


    【解决方案1】:

    您可以将CustomType 对象的键键入为optional

    (Try)

    // @flow strict
    
    export type CustomType = {
      a?: string,
      b?: boolean,
      c?: boolean,
      d?: boolean,
      e?: boolean
    };
    let d = true;
    let b = true;
    let customType: CustomType = {
            d,
            b,
            c: true,
     }
    
    class Custom{
      constructor(customType: CustomType = {}) {}
    }
    
    let custom = new Custom(customType);
    

    或者,您可以使用$Shape<T>。它只允许您传递您感兴趣的密钥:

    (Try)

    // @flow strict
    
    export type CustomType = {
      a: string,
      b: boolean,
      c: boolean,
      d: boolean,
      e: boolean
    };
    let d = true;
    let b = true;
    let customType: $Shape<CustomType> = {
            d,
            b,
            c: true,
     }
    
    class Custom{
      constructor(customType: $Shape<CustomType> = {}) {}
    }
    
    let custom = new Custom(customType);
    

    【讨论】:

    • $Shape 的缺点是失去智能感知
    猜你喜欢
    • 2019-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    • 2014-04-05
    • 1970-01-01
    • 2012-07-13
    相关资源
    最近更新 更多