我是新手,目前正在从事严格流程的项目。我有一个传递给类的类型别名。片段可以在这里找到
// @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都存在。最好的解决方法是什么?
您可以将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)