2

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)
}
6
  • WHy do you need to use generic at all ? T does not affect return type Commented May 15, 2022 at 9:05
  • you cannot create an instance of an object via generics in that way. interfaces don't exists when you compile your code Commented May 15, 2022 at 9: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 Commented May 15, 2022 at 9:19
  • @Jacek could you please provide an exmaple ? I mean, very small example Commented May 15, 2022 at 9: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. Commented May 15, 2022 at 13:17

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.