Get an interface of own properties from a class in TypeScript

Viewed 312

Consider the following class:

class Person {
  name: string = 'Shachar';
  age: number = 22;
  
  printPerson() {
    console.log(`name: ${this.name}, age: ${this.age}`);
  }
}

Is there a way to get an interface with the properties that would be "own" by an instance of this class? In this example, I want only the properties name and age, since printPerson will end up being part of the prototype of any instance, not own property.

Solutions that requires typing "name" and "age" explicitly are NOT acceptable since the class may have many properties and I would like to write them only once.

1 Answers

Feels like there should be a better answer to this, and perhaps there is, but as a workaround, can you split your example class into two separate classes -- one which contains your properties and one which contains your methods? For example:

class PersonProperties {
    name: string = 'Shachar';
    age: number = 22;
}

class Person extends PersonProperties {
    printPerson() {
        console.log(`name: ${this.name}, age: ${this.age}`);
    }
}

You can then either utilize the implicit interface of PersonProperties or create a custom one as you see fit, e.g.

interface IPersonProperties extends PersonProperties {};

var x:IPersonProperties = {
    age: 500000,
    name: ""
}

Perhaaps not ideal, but it should work.

Related