简体   繁体   English

Typescript默认属性值样式指南

[英]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. 第一个更干净,类似于C#,但第二个更接近编译输出的语法(如果创建定义文件),属性类型是显式的。

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 我已经看了https://www.typescriptlang.org/docs/home.htmlhttps://github.com/Microsoft/TypeScript/wiki/Coding-guidelineshttps://angular.io/guide/时尚指南

I don't know of an "official" style guide that specifies this anywhere. 我不知道在任何地方指定这个的“官方”风格指南。

Since ES2015, classes are part of JavaScript . 自ES2015以来, 类是JavaScript的一部分 If your TypeScript target version is ES6 or later, then the above both compile to 如果你的TypeScript 目标版本ES6或更高版本,那么以上都编译为

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. 此外, JavaScript中的类字段 (截至2017年7月)是第3阶段提案 ,这意味着它们最终会成为语言的机会很大。 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. 所有这一切都是我的说法,我不会太担心你的TS代码“更接近”编译的JS,因为这种差异最终会消失,在此之前,TypeScript的一个要点就是让你今天使用明天的JavaScript功能。 From the TypeScript Handbook : TypeScript手册

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. 在TypeScript中,我们允许开发人员现在使用这些技术,并将它们编译为适用于所有主流浏览器和平台的JavaScript,而无需等待下一版本的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! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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