如何省略错误:[ts] <class function name> 的推断类型引用了无法访问的“this”类型。类型注释是必要的

问题描述 投票:0回答:1

我想创建非常漂亮、流畅的 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
  • mac osx10.13.3
typescript visual-studio-code typescript2.0 vscode-debugger
1个回答
-1
投票

我刚刚收到此错误消息。

当您显式指定函数返回值的类型时,它就会消失:

public replace(): any {...}

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

© www.soinside.com 2019 - 2024. All rights reserved.