0

Let say I have this class and object from it

export class Person {
   constructor(name: string, age: number) { 
      this.name = name;
      this.age = age;
   }
   public name: string,
   public age: number
} 

const person = new Person();

Is there any way to get its properties' types like:

console.log(person.age.type) ????? => 'number' 
2
  • 1
    const person = new Person('name', 20); Then, typeof person.name gives 'string'. Commented Mar 10, 2023 at 7:50
  • The type of the actual value assigned to it? Or whatever you annotated in TypeScript?
    – deceze
    Commented Mar 10, 2023 at 7:51

1 Answer 1

3

Remember that all TypeScript-specific data like type annotations don't make it into the runtime. You can't materialize automatically at runtime anything you declare that is not native to JavaScript.

What you can do, however, whenever a variable or a field has bene assigned a value, is to ask what its type is with the typeof operator.

const str = "hello";
console.log(typeof str); // "string"

const person = new Person('Bob', 42);
console.log(typeof person.name); // "string"

Note, however, that you won't get any info on the type the field should have if the field holds no value:

const person = new Person(); // but the compiler should prevent this!
console.log(typeof person.name); // "undefined"

And, as a side note, remember that in TypeScript, when you define such very simple data classes and want to simplify notation, you can just add a visibility specifier to the constructor's parameters to turn them into fields that will automatically hold the passed values:

export class Person {
    constructor(public name: string, public age: number) { }
} 

Not the answer you're looking for? Browse other questions tagged or ask your own question.