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)
like, this shouldn’t give errors, right?
it not appears in VSC too:
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
You use the constructor wrong (you assign object values to the contstructor parameters instead of the other way around):
You have your declarations backwards.
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 dothis.property = someValue
See the MDN docs for additional details: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes