Skip to content

Const 类型参数

一句话解释

<const T> 使类型参数推断使用字面量类型而非拓宽——泛型的 as const。

用大白话说

类型参数上的 const 修饰符(TypeScript 5.0+)告诉 TypeScript 为该参数推断最窄可能类型——字面量类型而非拓宽的基础类型。没有 const:function first<T>(arr: T[]): T 用 ["a", "b"] 调用推断 T = string。有 const:function first<const T>(arr: readonly T[]): T 推断 T = "a" | "b"。这像 as const 但用于泛型类型参数——它自动应用窄推断,无需调用者添加 as const。要求:参数必须是 readonly(因为字面量类型是不可变的)。这防止意外修改推断的字面量类型。

示例

typescript
// Without const type parameter — T widens to string
function first<T>(arr: readonly T[]): T {
  return arr[0];
}
const r1 = first(["a", "b", "c"]); // type: string (widened)

// With const type parameter — T stays as literal union
function firstConst<const T>(arr: readonly T[]): T {
  return arr[0];
}
const r2 = firstConst(["a", "b", "c"]); // type: "a" | "b" | "c" (narrow)

// Practical: tuple inference
function pair<const T>(first: T, second: T): [T, T] {
  return [first, second];
}
const p = pair("hello", "world"); // type: ["hello" | "world", "hello" | "world"]

<const T> 防止拓宽:数组 ['a', 'b', 'c'] 推断 T 为 'a' | 'b' | 'c' 而非 string。类似 as const 但对泛型参数自动。

常见混淆

  • 容易混淆的对象: as const

    关键区别: as const 由调用者在特定值上应用。const 类型参数由函数作者在泛型声明上应用。as const 需要调用者记住;const 类型参数是自动的。它们实现相同的窄推断但从不同方向。

相关术语

相关资源

相关课程

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表