无法将对象字面量分配给`...`,因为对象字面量[1]中缺少属性`...`,但存在于`...`中

omo*_*ade 5 flowtype

我是新手,目前正在从事严格流程的项目。我有一个传递给类的类型别名。片段可以在这里找到

// @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);
Run Code Online (Sandbox Code Playgroud)

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

Jam*_*aus 5

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

尝试

// @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);
Run Code Online (Sandbox Code Playgroud)

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

尝试

// @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);
Run Code Online (Sandbox Code Playgroud)