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

标签 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 都存在。这里最好的解决方法是什么?

最佳答案

您可以键入 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> .它只允许您传递您感兴趣的 key :

( 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);

关于flowtype - 无法将对象文字分配给 `...`,因为对象文字 [1] 中缺少属性 `...` 但存在于 `...`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50621164/

相关文章:

javascript - 对于定义为枚举值到字符串的映射的类型,如何使用流程检查映射对象文字是否具有每个枚举值的键?

javascript - 从值位置流 javascript 泛型类型 "Cannot reference type ` CustomType`[1]。”

javascript - 访问嵌套流类型

javascript - 如何在流程中获取由 Promise 类型包装的类型?

reactjs - 如何让 Flow 了解码件将通过 cloneElement 接收所需的 props?

flowtype - 奇怪的 `Method cannot be called on possibly null/undefined value`

flowtype - Canvas 元素的正确类型

javascript - 流量: Getting error when using Map

javascript - 即使在 if 语句中包装后,Flow 仍认为该值为 null

javascript - 迭代 HTMLFormElement 元素时正确的 Flow 类型?