Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why typescript create duplicate assignment after compiling public parameter to constructor?

Tags:

typescript

I am new to typescript and was playing with compilation. Below file after compilation shows two assignments in js file, why is it so?

input file

class Student {
    constructor(public fname: string){
        this.fname = fname;
    }
}

output content

var Student = /** @class */ (function () {
    function Student(fname) {
        this.fname = fname;
        this.fname = fname;
    }
    return Student;
}());
like image 518
Tushar Raut Avatar asked Dec 19 '25 10:12

Tushar Raut


1 Answers

TypeScript includes a concise way to create and assign a class instance property from a constructor parameter.

Which means, rather than:

class TestClass {
  public name: string;

  constructor(name: string) {
    this.name = name;
  }
}

one can use:

class TestClass {
  constructor(public name: string) { }
}

In your code snippet you are mixing both the syntax which is resulting in double assignment.

like image 86
abhishek khandait Avatar answered Dec 21 '25 04:12

abhishek khandait