从Flow转TypeScript后,函数参数联合类型报错,求正确写法
Hey there! I totally get the confusion here—Flow and TypeScript have some subtle differences in how they handle function type definitions in object types, and that's exactly what's tripping you up.
Let's break down why your original code is throwing an error:
fnA(string, string | object): void; // ^ Unexpected token, expected ","
In Flow, you can omit parameter names when defining method signatures in a type. But TypeScript requires explicit parameter names before the type annotations, even if you don't plan to use the names elsewhere. That's why the parser throws a syntax error—it sees string and can't tell if it's a parameter name or a type (since parameter names can't be reserved type keywords like string anyway).
Your fnB line might seem like it works, but that's actually a false positive! fnB(string, any): void; is also invalid TypeScript syntax—it just might not be caught by your linter/editor right away.
Here are the two correct ways to write this in TypeScript:
1. Method Signature Style (similar to Flow, but with parameter names)
This keeps the method-like syntax you're used to, but adds required parameter names:
type Props = { fnA(arg1: string, arg2: string | object): void; // No more syntax errors! fnB(arg1: string, arg2: any): void; // Fixed this one too for consistency };
2. Arrow Function Property Style (more explicit, widely used in TS)
Many TypeScript developers prefer this style because it makes it clear that fnA is a property whose value is a function:
type Props = { fnA: (arg1: string, arg2: string | object) => void; fnB: (arg1: string, arg2: any) => void; };
Both styles are valid, but the arrow function approach is often easier to read for complex function types, and it aligns with how you'd define standalone function types in TypeScript.
The key takeaway: TypeScript needs parameter names for function parameters in object types—once you add those, your union type (string | object) works exactly like it does in Flow.
内容的提问来源于stack exchange,提问作者Alex

