1

I try to get properties name from generic interface in TypeScript, I have tried to create object and use keys property from Object, but I can do it. Can anyone helps me?

const getPropertiesByType = <T>(): string[] => {
  const emptyInstance: T = ?? 

  return Object.keys(emptyInstance)
}
Jacek
  • 11,661
  • 23
  • 69
  • 123
  • WHy do you need to use generic at all ? `T` does not affect return type – captain-yossarian from Ukraine May 15 '22 at 09:05
  • you cannot create an instance of an object via generics in that way. interfaces don't exists when you compile your code – R4ncid May 15 '22 at 09:09
  • @captain-yossarian I use some types to be returned by API and put them in grid. So I need to specify columns - properties name from interface – Jacek May 15 '22 at 09:19
  • @Jacek could you please provide an exmaple ? I mean, very small example – captain-yossarian from Ukraine May 15 '22 at 09:20
  • You essentially can't do this with pure TypeScript. TypeScript just describes what happens in JavaScript; it does not generally add functionality, Your code would emit as `() => {const emptyInstance = ???; return Object.keys(emptyInstance);}` so there's no input to that function and thus nothing for `emptyInstance` to be initialized with. You can maybe add build steps to transform your TS to JS in a way that adds relevant type info; see the answers to the linked questions for more information. – jcalz May 15 '22 at 13:17
  • My advice is to write your algorithm in pure JS and then add types to it; how would you do this without interfaces? My guess is that this is an XY problem since you have some underlying use case which makes you think you need to get property keys from interfaces. You may want to open a new question with questions about your underlying use case instead of trying to get runtime type reflection. – jcalz May 15 '22 at 13:19

0 Answers0