【问题标题】:How to omit error : [ts] The inferred type of <class function name> references an inaccessible 'this' type. A type annotation is necessary如何省略错误:[ts] <class function name> 的推断类型引用了无法访问的“this”类型。需要类型注释
【发布时间】:2018-09-05 02:00:32
【问题描述】:

我想创建非常漂亮、流畅的 typescript api,但我得到了 错误:

[ts] 'firstLevelFunction' 的推断类型引用了一个不可访问的 'this' 类型。需要类型注释。

我的班级架构:

class SomeClassAPI { 

    // in my case (on the picture at bottom)
    // 'firstLevelFunction(...)' equal 'replace(...)' method ,
    // from class CodeTransform  )
    public firstLevelFunction() { 
        const self = this; // ERROR
        // const self = this as any; // OK but not typechecking

        return {
            secondLevelFunction() {
                return {
                    thirdLevelFunction() {
                        // ....
                    }
                }
            }
        }
    }
}

只有当我使用“thirdLevelFunction”做 api 时,我才会得到这个东西。 我怎样才能忽略这个错误

我的 tsconfig.json

{
    "compileOnSave": true,
    "compilerOptions": {
        "declaration": true,
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "allowSyntheticDefaultImports": true,
        "importHelpers": true,
        "module": "commonjs",
        "skipLibCheck": true,
        "sourceMap": true,
        "target": "es5",
        "typeRoots": [
            "node_modules/@types"
        ],
        "lib": [
            "dom",
            "es2015"
        ],
        "types": [
            "node"
        ],
        "rootDir": "./src",
        "outDir": "dist"
    },
    "include": [
        "src/**/*"
    ],
    "exclude": [
        "node_modules",
        "preview",
        "docs",
        "dist",
        "bundle",
        "example",
        "examples",
        "tests",
        "tmp-src"
    ]
}

这是错误在 vscode 中的样子:

我正在使用:

  • 打字稿 2.6.2
  • vscode 1.21.1
  • ma​​c osx 10.13.3

【问题讨论】:

  • 您能否更清楚地了解错误发生的确切位置?您在描述中没有提到isomorphicreplace()。此外,您在上面提供的代码不是有效的 TypeScript(类定义周围没有括号)。也许发布一个可以重现该问题的最小示例会有所帮助。
  • @err1100 现在尝试在带有 tsconig.json 的 vscode 中使用 SomeClassAPI 类(上图)。
  • 当我复制并粘贴您提供的代码、创建 SomeClassAPI 的新实例并调用 firstLevelFunction() 时,我没有收到来自 VSCode 的任何智能感知错误,也没有收到来自 tsc 的编译器错误。
  • 嗯,我也遇到了这个错误。运气好吗?

标签: typescript visual-studio-code typescript2.0 vscode-debugger


【解决方案1】:

我刚刚收到此错误消息。

当你明确指定函数返回值的类型时,它就会消失:public replace: any() {...}

我猜 TS 在这种特定情况下无法推断返回类型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多