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

TypeScript中联合类型数组sort的参数为何被推断为any类型?

Why 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}[]), the sort callback expects parameters of type {version: number, a: string}.
  • For the second array type ({version: number, b: string}[]), the sort callback 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:

  1. Explicitly type the callback parameters
    Since both object types have a version property, 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 list ends up being, the version property will always exist.

  2. Adjust the list type to an array of a union
    If your use case allows it, redefine list as 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 a and b have a version property, so it doesn't need to fall back to any.

内容的提问来源于stack exchange,提问作者weaponhe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 09:17:52