Suggestion: Add the nameof compile-time operator to convert property and function names into strings
See original GitHub issueI 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));
Issue Analytics
- State:
- Created 9 years ago
- Reactions:329
- Comments:174 (42 by maintainers)
Top GitHub Comments
Why after all this time, TS still has no mechanism to (e.g.
nameof
) to eliminate MAGIC STRINGS?I don’t understand why this thread has so much begging, justifications, and use cases. It’s a no brainer - this should be a top priority. It’s the most horrible part of JS which TS has not yet solved.
i don’t quite get this reluctance either
nameof
is merely a macros that transforms a property name identifier into a string literal at the syntax level, why is it such a big deal to add it?