Flow严格模式下CustomType属性缺失报错的最优修复方案咨询
Let's break down your issue and walk through the best fixes, tailored to your use case.
First, let's clarify the two main problems in your code:
- Your
customTypevariable doesn't match theCustomTypedefinition (it's missingaandeproperties) - The
Customclass constructor's default value{}doesn't align with theCustomTypetype requirement
Scenario 1: You Need to Pass a Complete CustomType Object
This is the strictest approach, which aligns perfectly with Flow's strict mode rules:
Step 1: Fix the customType Variable
You must include all required properties defined in CustomType:
// @flow strict export type CustomType = { a: string, b: boolean, c: boolean, d: boolean, e: boolean }; let d = true; let b = true; // Add the missing `a` (string) and `e` (boolean) properties let customType: CustomType = { d, b, c: true, a: "your-string-value", // Required string property e: false // Required boolean property };
Step 2: Fix the Constructor Type & Default Value
If you want to allow omitting the constructor argument, provide a valid CustomType default object instead of an empty {}:
class Custom{ // Explicitly type the parameter, and use a valid default constructor(customType: CustomType = { a: "default-a", b: false, c: false, d: false, e: false }) {} } // Now both of these work: let customWithCustomType = new Custom(customType); let customWithDefault = new Custom();
If you require that the argument must be passed (no default), simply remove the default value:
class Custom{ constructor(customType: CustomType) {} } // Only valid with a complete CustomType object let custom = new Custom(customType);
Scenario 2: You Want to Allow Partial CustomType Objects
If your business logic doesn't require all properties to be present, mark non-required properties as optional in your type definition using ?:
// @flow strict // Mark optional properties with `?` export type CustomType = { a: string, // Keep this as required if needed b?: boolean, c?: boolean, d?: boolean, e?: boolean }; let d = true; let b = true; // Now only the required `a` property is mandatory let customType: CustomType = { d, b, c: true, a: "your-string-value" }; class Custom{ // Empty object default is now valid, since all non-required properties are optional constructor(customType: CustomType = {}) {} } let custom = new Custom(customType);
Why This Happens
In Flow strict mode, object literals must exactly match the target type's required properties—no exceptions. The empty object {} you used as a constructor default doesn't meet the CustomType requirements, and your initial customType variable was missing two mandatory properties, hence the errors.
内容的提问来源于stack exchange,提问作者omoabobade

