Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get name of variable in typescript

Tags:

How can I get a variables name in typescript? I want something like this:

var name = "Foo";
alert(getVariableName(name)); //Prints "name"
like image 638
Kenneth Bo Christensen Avatar asked Mar 22 '15 05:03

Kenneth Bo Christensen


People also ask

How do you name a variable in TypeScript?

The type syntax for declaring a variable in TypeScript is to include a colon (:) after the variable name, followed by its type. Just as in JavaScript, we use the var keyword to declare a variable. Declare its type and value in one statement.

What is ?: In TypeScript?

What does ?: mean in TypeScript? Using a question mark followed by a colon ( ?: ) means a property is optional. That said, a property can either have a value based on the type defined or its value can be undefined .

What is a string variable name?

A string variable is identified with a variable name that ends with the $ character. A string array variable has the $ character just before the left bracket that holds the array index. The variable name must begin with a letter and consist of 30 or fewer characters, including the $ character.

When to use let and VAR in TypeScript?

The let statement is used to declare a local variable in TypeScript. It is similar to the var keyword, but it has some restriction in scoping in comparison of the var keyword. The let keyword can enhance our code readability and decreases the chance of programming error.


2 Answers

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));
like image 124
Titian Cernicova-Dragomir Avatar answered Oct 16 '22 17:10

Titian Cernicova-Dragomir


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.

like image 42
basarat Avatar answered Oct 16 '22 18:10

basarat