不能将对象文字分配给`...`因为对象文字[1]中缺少属性`...`但是存在于`...`

时间:2018-05-31 09:37:38

标签: flowtype

我是新流程,目前正在开发一个流程严格的项目。我有一个类型别名传递给一个类。可以找到代码段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。这里最好的解决方法是什么?

1 个答案:

答案 0 :(得分:3)

您可以将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);