TypeScript getter setter约定 [英] TypeScript getter setter convention

查看:72
本文介绍了TypeScript getter setter约定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TypeScript中类属性的约定(标准)是什么?

What is the convention (standard) in TypeScript for class attributes?

在angular 2演示中(angular.io的Heroes Tour),所有属性均设置为public:

In the angular 2 demo (The Heroes Tour from angular.io) all attributes are set to public :

export class Hero {
   id: number;
   name: string;
}

因此可以通过两种方式实例化它们:

So they can be instanciated both ways :

var hero: Hero = new Hero();
hero.id = 0;
hero.name = "hero";

var hero2: Hero = {id : 0, name: "hero"};

是否有Java样式约定(例如这样):

Is there a Java style convention (like this) :

export class Hero {
   private id: number;
   private name: string;

   setId(id: number): Hero {
      this.id = id;
      return this;
   }

   setName(name: string): Hero {
      this.name = name;
      return this;
   }

   getId(): number {
      return this.id;
   }

   getName(): string {
      return this.name;
   }
}

声明(例如):

var hero: Hero = new Hero();
hero.setId(0).setName('hero');

var hero2: Hero = new Hero().setId(0).setName('hero');

推荐答案

是因为要设置想要使用Java样式的各个属性的额外代码吗?如果是这样,您可以在类的构造函数中声明属性.

Is it because of the extra code around setting the individual properties that you want to use the Java style? If so you can declare the properties in the constructor of the class.

英雄阶层

export class Hero {
 constructor(public id?: number, public name?: string) {}
}

声明

const hero1 = new Hero(1, 'hero');
const hero2 = new Hero();

这篇关于TypeScript getter setter约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆