Dinu
Dinu

Reputation: 93

What should be the type for an object method returning this in Typescript

Say I have an object like below:

const console = {
  write(text: string) {
    /* logic */
    return this;
  },
  writeLine(text: string) {
    /* logic */
    return this;
  }
};

What should be the return type of write and writeLine methods here?

I know that we can define an interface and set that as the return type but is there any other way to set the type that refers to the object?

Upvotes: 2

Views: 34

Answers (1)

You can define return type explicitly in this way:

const _console = {
  write(text: string): typeof this {
    /* logic */
    return this;
  },
  writeLine(text: string): typeof this {
    /* logic */
    return this;
  }
};

Playground

Or you can define your console as a class and just use this:

class Console {
  write(text: string): this {
    /* logic */
    return this;
  }
  writeLine(text: string): this {
    /* logic */
    return this;
  }
};

Playground

I hope it makes ESLint happy :D

Upvotes: 1

Related Questions