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

TypeScript中Pick工具类型在函数返回类型校验中为何表现不一致?

Why Do These Two 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">). Since name isn’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 to const data. TypeScript infers data’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 return data, TypeScript uses its standard structural type compatibility rule: since data has all the properties required by Pick<TestInterface, "id"> (just id), 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 18:07:34