1

What is a good approach to giving this a type annotation in a constructor?

function Client(options: ClientOptions) {
    const defaultOptions = { 
        host: 'ws://127.0.0.1',
        port:  8080,
        logger: function() {
            const prefix = "LOG:";
            console.log.call(null, prefix, ...Array.from(arguments))
        },
        maxTime: 30000, 
        startFromTransactionId: 1
    };

    Object.assign(this, { ...defaultOptions, ...options });

    this.transactionsCounter = 0;
    this.requestCallbacks  {};
    this.socket = null;
}

[ts] 'this' implicitly has type 'any' because it does not have a type annotation.

Elaboration

My editor shows me red squiggly lines beneath each use of the this keyword in this constructor. I get a [ts] warning that this does not have any type annotation.

How should I go about adding type annotation to this?

2
  • Not clear with your question Can you little bit elaborate it ? Commented Jan 30, 2019 at 12:09
  • 1
    @CodeChanger: Thanks for trying to help. Let me know if my elaboration still is not clear enough Commented Jan 30, 2019 at 12:14

2 Answers 2

2

The type of this can be defined as a fake parameter, in first position:

function Client(this: any, options: ClientOptions) {
    // ...
}

Or, this kind of error can be disabled by setting the compiler option --noImplicitThis to false.

Sign up to request clarification or add additional context in comments.

Comments

0

Since you are using typescript you could use Class instead of this approach. There you wont have any errors with using this.xxx And as a bonus you will get type hinting when using the class

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.