检查值是私有还是只读

Daa*_*v z 2 typescript angular

说我有一节课:

export class ItemType{

  readonly itemtype_id: number;
  public name :string;

  constructor(itemtype_id: number, name: string) {
    this.itemtype_id = itemtype_id;
    this.name = name;
  }
}
Run Code Online (Sandbox Code Playgroud)

现在我已经创建了一个可编辑标签的单独组件.

<div class="row">
  <div class="col-xs-4">
    <h4><span class="xvrfont padding">{{label}}</span></h4>
  </div>
  <div class="col-xs-2"></div>
  <div class="col-xs-5">

    <div *ngIf="editing">
      <input #editableField
             [required]="required"
             (blur)="onBlur($event)"
             [name]="value"
             [(ngModel)]="value"
             [type]="type"
             [placeholder]="label"
             (keyup.enter)="onEnter()"
             (mouseover)="$event.target.select()"
             />
    </div>
    <div *ngIf="!editing">
      <h4 title="Click to edit" (click)="edit(value);" (focus)="edit(value);" tabindex="0" class="inline-edit">{{value}}&nbsp;</h4>
    </div>


  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

当我调用此组件时,我希望该字段可以根据属性是否为只读来编辑.如果该属性是只读的,则该字段不应该是可编辑的.如果不是,它应该.

<app-editable-field [isEditable]={{**check if the property is readonly**}} label='Label" [required]="true" type="text"></app-editable-field>
Run Code Online (Sandbox Code Playgroud)

有没有一种简单的方法可以检查类中的属性是否为readOnly/private?

Joh*_*auß 5

问题是你的Typescript被编译成Javascript,总是记住这一点.

因此,所有类型和公共/私有检查(以及使得Typescript非常棒的所有其他东西)只能在编译时执行.一旦将其编译为Javascript,所有这些信息就会丢失.这意味着由于浏览器正在执行普通的Javascript,因此在运行时没有真正的方法来检查成员是私有还是只读.

为了说明这一点,请查看此链接以查看您的Typescript类被编译为什么:TypeScript Playground

正如dsfq在注释中指出的那样,使用布尔成员来指示该字段是否可编辑.