我是新流程,目前正在处理流程严格的项目。我有一个类型别名被传递给一个类。可以找到该片段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/