4

我想创建非常漂亮、流畅的打字稿 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
  • macOS 10.13.3
4

1 回答 1

0

我刚刚收到此错误消息。

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

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

于 2020-10-06T14:29:24.057 回答