2

I am trying to set up a VSCode environment for working with TypeScript v2.03

I start out with a simple vanilla javascript snippet I can test out in node via the integrated terminal.

function Person() {
    this.name = "";
}

Person.prototype.age = 0;

let me = new Person();

I insert into the Typescript Playground website and it compiles fine with no complaints.

But when I create a new file in VSCode, the VSCode editor complains:

enter image description here

And if I run webpack with the ts-loader plugin I get this error: enter image description here

When I run 'tsc src/test.ts' it compiles without complaints.

My questions:

  1. Is my code wrong or is this just a complaint I'm supposed to ignore?
  2. Is there anyway to tell VSCode to stop showing me the complaint?
2
  • 1
    Please include the error messages as text, rather than images. There's no way for search engines to index an image, and some of us are old and need help reading :). Commented Oct 3, 2016 at 17:59
  • think of a better title ... Commented Oct 3, 2016 at 18:07

1 Answer 1

2

One of the main benefits to TypeScript over JavaScript is explicitly defined types. In this case a better way to configure Person would be to define it as a class. This will restrict assignment to the known members on the type Person.

class Person {
    name: string;
    age: number;

    constructor(){
      this.name = "";
    }
}

let me = new Person();
// assignments to known members on the type Person
me.age = 21;
Sign up to request clarification or add additional context in comments.

3 Comments

I tried your modification adding the ':any', it does not clear the error. I still get errors: "TS2350: Only a void function can be called with the 'new' keyword." and "error TS7009: 'new' expression, whose target lacks a construct signature, implicitly has an 'any' type." I know TS and VSCode cant be this wrong so I must have a bad configuration or something. The class example works but I have a project with a lot of existing function constructors which I don't want to convert to classes and I was hoping existing JS code would just work.
@tommy - I modified my answer and removed that part as I can see now I was wrong as to my assumption of why it failed in TS. Let me play with it for one more second to see why it failed. The other part though is one of the ways that you should be using typescript which differs from previous approaches used in javascript. I say one way because it could also be done using interfaces without a concrete type.
I want to reiterate that I can type in my original example in the TypeScript playground with NO complaints. So it must be an issue with the way I have VSCode set up.

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.