0

I'm using TypeScript to detect typing problems in plain JavaScript. This is possible via a limited set of JSDoc tags.

However, there's one strange issue with it. When a member is created in the constructor, its type isn't set.

In the screenshot below, VS Code complains correctly about assigning a number to a string inside the update method, and directly on an instance. But it doesn't notice the incorrect assignment in the constructor.

This only seems to happen in the constructor, as creating a member in the update method does mark the typing issue.

Is there a way to force these type checks also in the constructor?

VS Code view with squiggles

Code:

// @ts-check

function MyClass() {
    /** @type {string} */
    this.str = 0;
};

MyClass.prototype.update = function() {
    this.str = 0
    /** @type {number} */
    this.num = ""
}

let inst = new MyClass()
inst.str = 0
inst.num = ""
3
  • 1
    Please don't use images for code. Commented Nov 13, 2018 at 14:55
  • Have you tried using @member {string}? Commented Nov 13, 2018 at 15:46
  • @member isn't supported for TypeScript. I did try it, but then it doesn't complain about anything. And the reason I used an image is because otherwise it won't show the squiggles. But I'll add the code too. Commented Nov 13, 2018 at 15:56

1 Answer 1

2

Add /** @constructor */ above function MyClass to check it as a constructor. See the documentation.

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

1 Comment

Thank you, completely missed that part.

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.