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.assignignores anynullorundefinedsource objects — so something likeObject.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.assigntype definitions to handlenull/undefinedsources 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.assignlooked roughly like this:
The idea was to return the intersection of the target and source types, which works fine for valid object sources.assign<T, U>(target: T, source: U): T & U; - When you pass
nullas the source, TypeScript infersUasnull. Following the signature, it returnsT & 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-wisenullcontributes nothing to the result. Back then, TypeScript didn't have special handling fornull/undefinedin this context; it just applied the generic intersection blindly. - Later versions fixed this by adding overloads that explicitly handle
null/undefinedsources, ensuring the return type matches what actually happens at runtime.
内容的提问来源于stack exchange,提问作者Lee Benson
相关产品推荐
相关产品推荐

