TypeScript中Pick工具类型在函数返回类型校验中为何表现不一致?
Pick Return Type Behaviors Differ in TypeScript? Absolutely, this is expected behavior in TypeScript—let me break down why these two functions act differently using your example:
interface TestInterface { id: number; name: string } function tmp1(): Pick<TestInterface, "id"> { return { id: 123, name: "projectName", // Error: excess property } } function tmp2(): Pick<TestInterface, "id"> { const data = { id: 123, name: "projectName", } return data // No error }
The Key Difference: Excess Property Checks (Freshness)
TypeScript has a special guard called excess property checks that only applies to object literals used directly in assignments or return statements. Here's how it plays out:
In
tmp1: You’re returning an object literal directly. TypeScript treats this as a "fresh" object and runs an extra strict check to ensure it doesn’t include properties not defined in the target type (Pick<TestInterface, "id">). Sincenameisn’t part of that target type, it throws an error—this is intentional, designed to catch typos or accidental extra properties you might not have meant to include.In
tmp2: First, you assign the object toconst data. TypeScript infersdata’s type as{ id: number; name: string }(it doesn’t apply excess checks here because you’re not assigning to an explicit type yet). When you returndata, TypeScript uses its standard structural type compatibility rule: sincedatahas all the properties required byPick<TestInterface, "id">(justid), it’s considered compatible. Excess property checks don’t trigger here because you’re returning a variable, not a fresh object literal.
A Quick Recap
- Excess property checks = strict guard for fresh object literals assigned directly to a specific type.
- Structural compatibility = flexible check for variables/values, as long as they have all required properties (extra properties are allowed).
This behavior has been consistent across TypeScript versions (including your 4.3.5) and is part of how TypeScript balances type safety with flexibility.
内容的提问来源于stack exchange,提问作者Flrande Flrande

