Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize variables in constructor or in declaration

When using ReactJS with TypeScript, is it better to initialize class variables in the constructor or when the class variable is being declared? It works fine either way and the transpiled javascript looks the same either way.

export class MyClass extends React.Component<iProps, {}> {
      private myName: string = "Hello";

      constructor(props: iProps) {
         super(props);

         this.myName= "Hello";
      }
}
like image 483
Lambert Avatar asked Sep 21 '16 14:09

Lambert


1 Answers

It's exactly the same, for example:

class MyClass1 {
      private myName: string = "Hello";
}

Compiles to:

var MyClass1 = (function () {
    function MyClass1() {
        this.myName = "Hello";
    }
    return MyClass1;
}());

And:

class MyClass2 {
      private myName: string;

      constructor() {
         this.myName = "Hello";
      }
}

Compiles to:

var MyClass2 = (function () {
    function MyClass2() {
        this.myName = "Hello";
    }
    return MyClass2;
}());

(code in playground)

As you can see the compiled versions are identical (except for the class names).
So you can use which one you find more elegant.

As for react, you can use the props which are passed to the constructor.
When using es6 style classes with react components then your initial state is assigned in the constructor and not using the getInitialState method.
If your initial state is a function of the props then you'll need to use those in the constructor.

like image 102
Nitzan Tomer Avatar answered Nov 02 '22 23:11

Nitzan Tomer