【问题标题】:Typescript, expected 0 arguments but got one (this)打字稿,预期 0 个参数,但有一个(这个)
【发布时间】:2021-09-03 16:30:51
【问题描述】:

当我遇到此错误时,尝试将一些 javascript 代码更改为 typescript:

这很令人困惑,因为它是用参数输入的

interface Command {
  execute: (client: Client, message: Message) => void;
  init: (this: this) => void;
  help: {
    name: string;
    aliases: string[];
  };
  conf: {
    location: string;
  };
}

它甚至声明它需要一个参数:

这是我试图传递this 的原因吗?我不太清楚为什么会这样。


我的 tsconfig.json

{
  "compilerOptions": {
    "baseUrl": ".",
    "outDir": "build",
    "module": "esnext",
    "target": "es5",
    "lib": [
      "es6",
      "dom",
      "esnext.asynciterable"
    ],
    "sourceMap": true,
    "allowJs": true,
    "jsx": "react",
    "moduleResolution": "node",
    "rootDir": "src",
    "forceConsistentCasingInFileNames": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "suppressImplicitAnyIndexErrors": true,
    "noUnusedLocals": true,
    "skipLibCheck": true,
    "allowSyntheticDefaultImports": true
  },
  "exclude": [
    "node_modules",
    "build",
    "scripts",
    "acceptance-tests",
    "webpack",
    "jest",
    "src/setupTests.ts"
  ]
}

【问题讨论】:

    标签: typescript


    【解决方案1】:

    使用类似于名为 this 的参数键入的函数不会将其作为参数,而是作为调用上下文。

    如果props 是您期望的this - 命令,看起来就是这样 - 您只需要正常调用它:

    props.init();
    

    这会将props 对象作为this 传递给函数,TypeScript 将能够识别它。

    对于其他情况,要将不同的this 传递给函数,请使用.call,例如:

    props.init.call(someOtherThis);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-13
      • 2018-11-18
      • 1970-01-01
      • 2018-05-29
      • 2018-11-24
      • 1970-01-01
      • 2020-11-07
      • 2022-01-24
      相关资源
      最近更新 更多