0

I am implementing an application with Typescript and I have created a class with the following fields:

export class Car {
   name: string;
   model: string;
   year: number;
   saleDate: Date;
   seller: User;
}

Now I create an instance of that class in this way:

var myCar = new Car();

Can I go through the fields of the class and get the format of each one? It would be something like this (but it does not work):

for(var field in myCar) {
   console.log(typeof field);
}
// console result (it does not work):
// string
// string
// number
// Date
// User

This case actually always returns 'string'. It makes sense, the key is really the name of the field, not the field itself.

Greetings.

Manish Balodia
  • 1,863
  • 2
  • 23
  • 37
Jose Sabater
  • 83
  • 4
  • 13
  • `field` is the **name** of the property. To get the actual property, use `myCar[field]`. Or use [`Object.values`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values) or [`Object.entries`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries). – T.J. Crowder Aug 03 '18 at 12:45
  • [typeof](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof#Description) does not really work with non-primitives, all objects just come out as `object`. You can try out [instanceof](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof) Helpful SO [post about instanceof](https://stackoverflow.com/a/6625960/2033671) –  Aug 03 '18 at 12:50

0 Answers0