How can I get a variables name in typescript? I want something like this:
var name = "Foo";
alert(getVariableName(name)); //Prints "name"
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 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 .
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.
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.
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));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With