Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript default property value style guide

Tags:

typescript

Is there any style guide defining how to set default property values? Hopefully official.

class MyClass {
    public foo = 'asdf';
}

and

class MyClass {
    public foo: string;
    constructor() {
        this.foo = 'asdf';
    }
}

both compile to

var MyClass = /** @class */ (function () {
    function MyClass() {
        this.foo = 'asdf';
    }
    return MyClass;
}());

The first is cleaner and similar to C# but the second is closer to the syntax of the compiled output ( and definition file if created) and the property type is explicit.

I've looked at https://www.typescriptlang.org/docs/home.html, https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines, and https://angular.io/guide/styleguide

like image 357
William Lohan Avatar asked Aug 17 '26 00:08

William Lohan


1 Answers

I don't know of an "official" style guide that specifies this anywhere.

Since ES2015, classes are part of JavaScript. If your TypeScript target version is ES6 or later, then the above both compile to

class MyClass {
    constructor() {
        this.foo = 'asdf';
    }
}

Furthermore, class fields in JavaScript are currently (as of July 2017) a Stage 3 proposal, which means that chances are good that they will eventually make it into the language. So eventually the compiled output may be:

class MyClass {
    foo = 'asdf';
}

All of this is my way of saying that I wouldn't worry too much upon having your TS code be "closer to" the compiled JS, since this difference will eventually disappear, and until then, one of the points of TypeScript is to let you use tomorrow's JavaScript features today. From the TypeScript Handbook:

In TypeScript, we allow developers to use these techniques now, and compile them down to JavaScript that works across all major browsers and platforms, without having to wait for the next version of JavaScript.


Okay, so my suggestion (not "official") is to do this:

class MyClass {
    public foo: string = 'asdf';
}

You've made the property type explicit and initialized it as a class field. The best of both worlds, right? Maybe?

Anyway, hope that helps; good luck!

like image 77
jcalz Avatar answered Aug 19 '26 19:08

jcalz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!