Supesu
Supesu

Reputation: 676

Typescript, expected 0 arguments but got one (this)

Trying to change some javascript code to typescript when I encountered this error: enter image description here

This is confusing because it's being typed with an argument

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

it even states that it expects one argument:
enter image description here

Is this something with me trying to pass in this? I'm not too sure why this is acting like this.


my 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"
  ]
}

Upvotes: 0

Views: 520

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370679

A function typed with something that looks like an argument named this doesn't take it as an argument, but as the calling context.

If props is the this you're expecting - the Command, which it looks like it is - you just need to call it normally:

props.init();

This will pass the props object as the this into the function, and TypeScript will be able to recognize it.

For other situations, to pass a different this into a function, use .call, eg:

props.init.call(someOtherThis);

Upvotes: 3

Related Questions