You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flow中将未定义属性访问转为错误?

How to Make Flow Throw Errors for Accessing Undefined Properties on Function Types

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 native Function interface, which allows dynamic property access (hence the any fallback 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 from Function means no unexpected any for 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:31:21