Skip to content

Generic 类型需要 1 类型实参(s)

错误信息

                Generic 类型需要 N 类型实参(s)
              

快速摘要

你 used generic 类型 or 函数不使用 providing 必需类型参数(s). TypeScript 需要 explicit 类型实参当 它们 cannot 是 inferred.

为什么发生

  • Using generic 类型 as 类型 annotation 不使用类型实参

  • Calling generic 函数哪里类型参数能't 是 inferred

  • Using generic 类不使用 specifying 类型实参

  • 类型 inference 失败 due 到 ambiguous or missing 上下文

最小示例

✗ 错误代码
const items: Array = [1, 2, 3]; // Array requires a type argument
✓ 修复代码
const items: Array<number> = [1, 2, 3];

Provide 类型实参: 数组<数字>.

如何诊断

  • 检查如果类型 or 函数有 generic 参数

  • Determine 如果 TypeScript 能 infer 类型实参从 usage

  • Look at 错误消息 for expected 数字的 类型实参

如何修复

  • Provide explicit 类型实参: 数组<字符串> or myFunc<字符串>(arg)

  • Provide 值那个允许 TypeScript 到 infer 类型参数

  • 设置默认类型参数: <T = 字符串> in declaration

如何预防

  • Use 默认类型参数当 sensible 默认 exists

  • 设计 APIs 所以类型参数能 是 inferred 从实参

相关资源

相关术语

← 返回语言