shawwwnL
shawwwnL

Reputation: 11

How can I get all the properties in Typescript Class with Optional properties

Let's say I have

class MyType {
  property1?: string,
  property2?: string
}

which all the properties are OPTIONAL.

How can I get an array of property names like:

["property1", "property2"]

I have tried

console.log(Object.keys(new MyType()))

which will return an empty array, because all the properties are optional.

Upvotes: 1

Views: 294

Answers (1)

Lin Du
Lin Du

Reputation: 102487

After transpiled, TS compiler will erase the optional properties. See TypeScript Playground

TS:

class MyType {
  property1?: string
  property2?: string
}

console.log(Object.keys(new MyType()))

transpiled JS:

"use strict";
class MyType {
}
console.log(Object.keys(new MyType()));

That's why you got an empty array.

Upvotes: 1

Related Questions