2

Given the following type:

class Foo {
    constructor(
        private one: string, 
        private two: string, 
        private three: string) {
    }
}

How can I have an array whose values are the type's properties?

e.g. I need to be able to get an array as:

['One', 'Two', 'Three']

Note I need to have the properties extracted from a type and not an instance otherwise I could simply use Object.keys(instanceOfFoo).

MaYaN
  • 6,683
  • 12
  • 57
  • 109

5 Answers5

7

You can use Reflect.construct() to get the keys, then use Object.keys() to convert that to an array.

Note: if the key doesn't have a default it won't be generated as you can see with four.

class Foo {
  constructor() {
    this.one = ''
    this.two = ''
    this.three = ''
    this.four
  }
}

console.log(Object.keys(Reflect.construct(Foo, [])))
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
1

If you just one to list the field's name from a class you can use the following:

let fields = Object.keys(myObj) as Array<MyClass>;

Hope it helps.

1

You need to instantiate const a = new Foo(); and access using Object.keys

class Foo {
    constructor(
        private one: string, 
        private two: string, 
        private three: string) {
    }
}

const a = new Foo();
console.log(Object.keys(a)); // ["prop"]

DEMO

EDIT: If you want to get from the type it is not possible since types won't be available once the code is compiled.

Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
1

Since the code above will be transpiled to following js code:

var Foo = (function () {
    function Foo(one, two, three) {
        this.one = one;
        this.two = two;
        this.three = three;
    }
    return Foo;
}());

I'd first extract the constructor using const c = Foo.prototype.constructor and the get the name of arguments from that. This thread shows how to do that.

Nima Hakimi
  • 1,382
  • 1
  • 8
  • 23
0

Scan the Object.keys(Foo.prototype)

eavichay
  • 507
  • 2
  • 7