skip to Main Content

EDIT: I fixed the backwards fields declaration

I’m new to Typescript, and I’m only familiar with CSS/HTML at the moment.
I started by creating a class to learn, but there’s an error, and even after searching, I haven’t found any answer that’s clear or that I understand.

//in mains.ts

class People
{
    name: string;
    age: number;
    
    constructor(name: string, age: number)
    {
        this.name = name;
        this.age = age;
    }
}

let pedro = new People("pedro", 16);
console.log(pedro.name, pedro.age);

But for some reason, I get this error pointing to the first field.
If I delete this field, the other one gets the same error.

Uncaught SyntaxError: Unexpected identifier 'name' (at main.ts:3:5)

i can't use the field

like, this shouldn’t give errors, right?
it not appears in VSC too:
no errors in VSC

What i expected?

it needs to work?
this is happening in the class, I don’t know if it also affects other things but I’m not experienced in TS
also, this is my HTML code, if needs to be shown…

<!DOCTYPE html>

<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        
        <!-- CSS -->
        <link href="style/mains.css" rel="stylesheet">
    </head>
    <body>
        <h1> Hi </h1>
        
        <!-- TS -->
        <script src="script/main.ts"></script>
    </body>
</html>

Any ideas?

2

Answers


  1. You use the constructor wrong (you assign object values to the contstructor parameters instead of the other way around):

     constructor(name: string, age: number) {
            this.name = name;  // Assign the parameter 'name' to 'this.name'
            this.age = age;    // Assign the parameter 'age' to 'this.age'
        }
    }
    Login or Signup to reply.
  2. You have your declarations backwards.

    class People
    {
        name: string;
        age: number;
        
        constructor(name: string, age: number)
        {
            this.name = name;
            this.age = age;
        }
    }
    
    

    Name and Age are your constructor’s parameters. The this keyword is to reference your class object. To assign a value to a class property, you would do
    this.property = someValue

    See the MDN docs for additional details: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search