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

TypeScript中Object.assign类型无效?2.6.2中为何类型为{} & null而非{}?

Hey there! Let's dive into your two TypeScript questions with clear, practical explanations:

1. Does Object.assign have invalid type issues in TypeScript?

Short answer: Yes, but mostly in older versions like 2.6.2. Here's the breakdown:

  • In runtime, Object.assign ignores any null or undefined source objects — so something like Object.assign({}, null) just returns {} as you'd expect.
  • But in older TypeScript versions (pre-2.8ish), the type system didn't account for this edge case properly. This led to invalid, counterintuitive inferred types (like {} & null) that don't match the actual runtime behavior.
  • Modern TypeScript versions (from around 2.8 onwards) fixed this by updating the Object.assign type definitions to handle null/undefined sources correctly, so you'll get the expected return type (just {} in the example above) without weird cross types.
2. Why does Object.assign({}, null) get inferred as {} & null instead of just {} in TypeScript 2.6.2?

This all boils down to how the Object.assign type was defined in that specific version. Let's break it down:

  • In TS 2.6.2, the core generic type signature for Object.assign looked roughly like this:
    assign<T, U>(target: T, source: U): T & U;
    
    The idea was to return the intersection of the target and source types, which works fine for valid object sources.
  • When you pass null as the source, TypeScript infers U as null. Following the signature, it returns T & U — which is {} & null.
  • The problem here is that the type system didn't reflect the runtime behavior: even though the type says {} & null, runtime-wise null contributes nothing to the result. Back then, TypeScript didn't have special handling for null/undefined in this context; it just applied the generic intersection blindly.
  • Later versions fixed this by adding overloads that explicitly handle null/undefined sources, ensuring the return type matches what actually happens at runtime.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:23:19