简体   繁体   中英

Typescript default property value style guide

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM