0

Is it possible to have such function or design something similar?

class Test {
  testProperty: string;
  secondTestProperty: string;
}

function propAsString(input: any) {
  ...
}

let test = new Test();
console.log(propAsString(test.testProperty)); // output 'testProperty'
console.log(propAsString(test.secondTestProperty)); // output 'secondTestProperty'
Cute pumpkin
  • 342
  • 3
  • 17
  • 3
    What problem are you trying to solve with this? It seems like you would need to have the property name, to access the property name? – DBS Mar 20 '23 at 09:49
  • You can find your answer here: – alieb Mar 20 '23 at 09:52
  • Initial problem I have is comparing two objects, but allowing some of the properties to be ignored. Comparing by obj keys and filtering out ones I want to ignore is not a problem. The problem is to add those undesired keys in an array to later filter. I do not want to add strings implicitly, because ts compiler would not be able to see them later, and renaming of those properties wont work. – Cute pumpkin Mar 20 '23 at 09:53
  • Sorry but no. Accepted option is no longer recommended by author, other option requires to put properties like string. – Cute pumpkin Mar 20 '23 at 11:39
  • Have you actually read past the first sentence of the accepted answer? To at least "Option 2" in the same accepted answer. Yes, it requires putting the properties as strings, but it gives compile time error if you misspell. – GSerg Mar 20 '23 at 11:45
  • I did. Compile time error is better than nothing, but its not what I am looking for. Renaming wont work, and you would need to run the code (in my case - visit the page) to encounter it. And having your code littered with string literals is just horrible. – Cute pumpkin Mar 20 '23 at 11:50
  • 2
    Well, sometimes the answer is no. You can subscribe to the [corresponding feature request](https://github.com/microsoft/TypeScript/issues/1579) but it's been out there for nine years. – GSerg Mar 20 '23 at 12:22

0 Answers0