TypeScript中联合类型数组sort的参数为何被推断为any类型?
a and b Are Inferred as any in Your Sort Callback Let's break this down step by step to make it clear.
First, let's look at how you've typed your list variable:
const list: ({ version: number, a: string }[]) | ({ version: number, b: string }[]) = [];
This is a union of two distinct array types — either it's an array of objects with version and a, or an array of objects with version and b. Important note: this is not the same as an array of a union type (which would be ({ version: number, a: string } | { version: number, b: string })[] — notice where the | is placed).
Now, when you call sort() on this union of arrays, TypeScript needs to figure out what type the callback parameters a and b should have. Here's the core issue:
- For the first array type (
{version: number, a: string}[]), thesortcallback expects parameters of type{version: number, a: string}. - For the second array type (
{version: number, b: string}[]), thesortcallback expects parameters of type{version: number, b: string}.
TypeScript can't resolve a single concrete type that works for both scenarios. The two object types don't share a common supertype that TypeScript can automatically infer here (beyond a generic object, which doesn't guarantee the version property exists). Since it can't pin down a valid type for a and b, it falls back to any — that's why you see the error.
Quick Fixes
If you want to resolve the error, here are a couple of straightforward options:
Explicitly type the callback parameters
Since both object types have aversionproperty, you can explicitly define a minimal type that captures this shared trait:list.sort((a: { version: number }, b: { version: number }) => a.version - b.version);This is safe because no matter which array type
listends up being, theversionproperty will always exist.Adjust the
listtype to an array of a union
If your use case allows it, redefinelistas an array where each element is either of the two object types (instead of a union of entire arrays):const list: ({ version: number, a: string } | { version: number, b: string })[] = []; list.sort((a, b) => a.version - b.version); // No error now!TypeScript can now infer that both
aandbhave aversionproperty, so it doesn't need to fall back toany.
内容的提问来源于stack exchange,提问作者weaponhe

