如何在Flow中将未定义属性访问转为错误?
Yep, this is a common gotcha with Flow's default handling of function types! The issue here is that Flow treats plain function types (like string => number) as inheriting from the native Function type, which allows access to any arbitrary property (falling back to any for unknown ones). But there's a straightforward fix to enforce strict checks here.
Solution: Use Exact Object Types with Call Signatures
Instead of defining your function type with the shorthand syntax, define it as an exact object type that includes only the call signature (and any explicit properties you want to allow). This tells Flow to reject access to any properties not explicitly declared.
Here's how to adjust your code:
type FakeType = {} // Define aFunc as an exact object with a call signature type aFunc = $Exact<{ (input: string): number, // Match your original function signature }> const b: aFunc = (input) => 1 const a: FakeType = b.whatTheHeck // Now Flow will throw an error!
When you try to access b.whatTheHeck now, Flow will complain that the property doesn't exist on aFunc—exactly what you want.
Why This Works
- The shorthand function type (
string => number) implicitly extends the nativeFunctioninterface, which allows dynamic property access (hence theanyfallback for unknown properties). - By wrapping the call signature in
$Exact<{}>, you're creating a strict type that only includes the properties you explicitly define. No hidden inheritance fromFunctionmeans no unexpectedanyfor random properties.
Optional: Keep Standard Function Methods
If you still want to allow access to standard Function methods like call, apply, or bind, you can explicitly include them in your exact type:
type aFunc = $Exact<{ (input: string): number, call: (thisArg: any, ...args: Array<string>) => number, apply: (thisArg: any, argsArray?: Array<string>) => number, bind: (thisArg: any, ...args: Array<string>) => aFunc, }>
This way you retain the useful built-in methods while still blocking access to undefined properties like whatTheHeck.
内容的提问来源于stack exchange,提问作者Grant Powell

