monstertjie_za
monstertjie_za

Reputation: 7813

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>;
}

Upvotes: 2

Views: 1326

Answers (1)

adiga
adiga

Reputation: 35253

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.

Upvotes: 5

Related Questions