0

In visual studio (or other common javascript/typescript IDEs), is there a simple way to rename properties in a class and automatically rename them in other places of the code where they are not in dot-notation as well?

The issue appears e.g. when properties are accessed with bracket notation obj["prop"] instead of obj.prop or when listing subsets of property names for some reason:

class C {
  constructor(
    public name: string,
    public age: number,
    public id: string
  ){}
};
let obj = new C("bob", 30, "abcdef");
let interesting = ["name", "age"];
console.log(`${interesting[0]}: ${obj[interesting[0]]}, ${interesting[1]}: ${obj[interesting[1]]}`);

I don't know of a good way to associate such strings with property names (apart from typing the strings as keyof C, which would at least give a compiler error after renaming) or IDEs smart enough to understand the relation.

There was the fancy idea of transforming everything into dot notation, with a method taken from a related question - namely converting a dummy function containing only an unused statement of the property access to string and parsing that. Then the common IDEs would rename it aswell. However, this introduces code which is completely unnecessary for the application itself and is not very robust unless written with extreme care - as e.g. Function.toString is partly implementation dependant.

Is there no practical way except doing most of it manually?

ASDFGerte
  • 4,695
  • 6
  • 16
  • 33
  • please don't format your classes as one-liners. it's hard to read. – falinsky Jul 09 '17 at 21:52
  • It is imposible. IDE is not humman. It can detect when your string contains string and when it contains property name very hardly. If you have defined interface why you do not access it via dot? – Misaz Jul 10 '17 at 05:57
  • Accessing properties by string index on object in JavaScript is way to hell. – Misaz Jul 10 '17 at 05:58
  • Well, i guess it is not possible. Unless there was a way to tell the IDE what property a string refers to (possibly via typescript types), it would be pretty hopeless anyways. – ASDFGerte Jul 11 '17 at 14:58

1 Answers1

0

It is possible if you replace hardcoded strings with variables that store property names

https://stackoverflow.com/a/47707719/2167309

var person = {};
person.firstname = 'Jack';
person.address = "123 Street";

function getPropertyName(obj, expression) {
    var res = {};
    Object.keys(obj).map(k => { res[k] = () => k; });
    return expression(res)();
}

let propertyName = getPropertyName(person, o => o.address);
console.log(propertyName); // Output: 'address'
artemnih
  • 4,136
  • 2
  • 18
  • 28