简体   繁体   中英

Object.keys(myObject) does not return properties of class in typescript

Why does:

let provider = new Provider();
var keys = Object.keys(provider);
console.log(keys);

return an empty array, when:

let provider = { Name: '', Surname: '' };
var keys = Object.keys(provider);
console.log(keys);

returns an array with the 2 properties in it?

Here is my Provider.ts :

export class Provider {
  public Id: string;
  public Name: string;
  public FriendlyName: string;
  public CompanyRegistrationNumber: string;
  public VatRegistrationNumber: string;
  public TfgUniqueReferenceNumber: string;
  public Since: Date;
  public Until: Date;
  public DefaultBillingDay: number;
  public DefaultProvisioningDay: number;
  public AllowsToProvisionProRata: boolean;
  public AllowsToBillProRata: boolean;
  public EmailAddress: string;
  public DateCreated: Date;
  public DateModified: Date;
  public UserCreated: string;
  public UserModified: string;
  public IsRetired: boolean;
  public ImageUrl: string;
  public ContactNumber1: ContactNumber;
  public ContactNumber2: ContactNumber;
  public PhysicalAddress: Address;
  public PostalAddress: Address;
  public FinancialSystemAccount: FinancialSystemAccount;
  public WholesaleProducts: Array<WholesaleProduct>;
  public ContactPeople: Array<ContactPerson>;
  public Batches: Array<Batch>;
  public BatchCandidates: Array<BatchCandidate>;
  public AllowableBatchTypes: Array<BatchType>;
}

Unless you initialize the properties, they are not actually created. You can check the trasnpiled Provider.js file and verify it. It's just a way to tell the compiler that, whenever we use it in the instance of Provider , force those predefined types.

Test it on the Typescript Playground

This class:

class Provider {
  public Id: string;
  public Name: string;
  public FriendlyName: string;
  public CompanyRegistrationNumber: string;
  public VatRegistrationNumber: string;
  public TfgUniqueReferenceNumber: string;
  public InitializedProp: string = '';
}

Gets transpiled to:

var Provider = (function () {
    function Provider() {
        this.InitializedProp = '';
    }
    return Provider;
}());

You can see that only the InitializedProp is created as a property in the transpiled constructor function.

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