Get name of variable in typescript

Expanding on basarat's answer, you need to create function that takes as a parameter a function that will contain the access to your variable. Because in JavaScript you can access the code of any function it then becomes a simple matter of using a regex to extract the variable name.

var varExtractor = new RegExp("return (.*);");
export function getVariableName<TResult>(name: () => TResult) {
    var m = varExtractor.exec(name + "");
    if (m == null) throw new Error("The function does not contain a statement matching 'return variableName;'");
    return m[1];
}

var foo = "";
console.log(getVariableName(() => foo));

One approach is to store such values in an object:

var o = {
    firstName: "Homer",
    lastName: "Simpson"
};

We can't get the name of o, but we can get the names (or "keys") of its two properties:

var k = Object.keys(o);
console.log(k[0]); // prints "firstName"

TypeScript is JavaScript at runtime. So the same limitations as there apply : Get the 'name' of a variable in Javascript

However you can do stuff like

alert(getVariableName(()=>name)) 

Here you would parse the body of the function passed into getVariableName and get that as a string.

Tags:

Typescript