Description
I would like to see the nameof
operator be considered for Typescript.
This feature was just added to C# description, and it is an elegant solution to a common issue in Javascript.
At compile time, nameof
converts its parameter (if valid), into a string. It makes it much easier to reason about "magic strings" that need to match variable or property names across refactors, prevent spelling mistakes, and other type-safe features.
To quote from the linked C# article:
Using ordinary string literals for this purpose is simple, but error prone. You may spell it wrong, or a refactoring may leave it stale. nameof expressions are essentially a fancy kind of string literal where the compiler checks that you have something of the given name, and Visual Studio knows what it refers to, so navigation and refactoring will work:
(if x == null) throw new ArgumentNullException(nameof(x));
To show another example, imagine you have this Person class:
class Person {
firstName: string
lastName: string
}
var instance : Person = new Person();
If I have an API that requires me to specify a property name by string (pretty common in JS), I am forced to do something like this:
someFunction(personInstance, "firstName");
But if I misspell firstName
, I'll get a runtime error.
So this is the type-safe equivalent:
someFunction(personInstance, nameof(Person.firstName));