Skip to content

'这个' implicitly 有类型 '任何'

错误信息

                '这个' implicitly 有类型 '任何'
              

快速摘要

使用 noImplicitThis 启用, TypeScript 错误当 `这个` 是 used in 函数不使用 determined 类型. 这个通常 happens in standalone 函数.

为什么发生

  • Using 这个 in 非-类函数不使用这个参数

  • Passing 类方法 as 回调不使用 binding

  • Using 这个 in 函数那个将 是 called 使用不同上下文

  • 事件处理函数哪里 这个 是设置通过框架

最小示例

✗ 错误代码
function handleClick() {
  console.log(this.value); // this is implicitly any
}
✓ 修复代码
function handleClick(this: { value: number }) {
  console.log(this.value);
}

添加 explicit 这个参数到 类型上下文.

如何诊断

  • 检查如果函数是 类方法 (这个是 输入) or standalone (这个是 任何)

  • Look for 这个 usage in 回调 or 事件处理函数

  • 检查如果 noImplicitThis 是启用 in tsconfig

如何修复

  • 添加 这个 参数: 函数 foo(这个: SomeType)

  • Use arrow 函数 (arrow 函数 don't 有它们的 own 这个)

  • Bind 函数: 这个.方法.bind(这个)

  • Move 函数到 类哪里 这个 是 determined

如何预防

  • Use arrow 函数 for 回调到 preserve 这个

  • 启用 noImplicitThis (部分的 strict 模式)

  • Explicitly 类型 这个 in standalone 函数

相关资源

← 返回语言