TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Suggestion: Add the nameof compile-time operator to convert property and function names into strings

Open Taytay opened this issue 11 years ago • 175 comments

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));

Taytay avatar Dec 30 '14 22:12 Taytay

See also #394 and #1003.

A fix for the magic string problem is a common requirement on the forums. Hoping to see an official proposal for this soon.

NoelAbrahams avatar Dec 31 '14 10:12 NoelAbrahams

Yeah, closing this as a dupe, suffice to say we definitely get the pain people feel here.

danquirk avatar Jan 06 '15 00:01 danquirk

I don't see this as dupe of any mentioned issues. This could be critical to support advanced minification together with metaprogramming. Currently there is no way how to get member string after minification. Though I don't have a clue how to add it to language without conflicting with other features...

In C# this works other way - you get unminified string. In Typescript I would need minified string. So maybe this could be actually different proposal :-) As unminified would be good too. Just some thoughs...

Bobris avatar Jul 27 '15 21:07 Bobris

Agree. Doesnt look like a duplicate. A nameof operator should be considered as a very good idea. Probably "easy" to implement too. I use typescript with angularjs and I like to create static string constants inside my controller/directive classes that I use when I register these classes in an angular module. Instead of hardcoding these names I would like to use nameof(MyDirectiveClass) instead. Its the same kind of problem that we experienced earlier with PropertyChanged events in WPF (before nameof/CallerMemberName) when you renamed stuff.

frodegil avatar Jul 28 '15 10:07 frodegil

Good point -- the other issues don't quite cover what this is talking about

RyanCavanaugh avatar Jul 28 '15 16:07 RyanCavanaugh

:thumbsup:

I'm using Typescript in a project at work, and am putting in a run-time duck type checker. The use case is de-serializing URL parameters.

If this feature was in the language, this is how I would expect the syntax to work:

class Foo {
    prop: string;
}

function isFoo(obj: Foo): boolean;
function isFoo(obj: any) {
    return (typeof obj === 'object') && 
              (obj !== null) && 
              (nameof(Foo.prop) in obj);
}

// Output for isFoo()
function isFoo(obj: any) {
    return (typeof obj === 'object') && 
              (obj !== null) && 
              ('prop' in obj);
}

Is that a correct assumption?

bryanerayner avatar Aug 19 '15 01:08 bryanerayner

@frodegil , that would be an awesome use case. Would reduce a lot of code-smell and repetitive copy/pasting from my daily work-flow.

@Bobris, one would hope that the minified strings for the purposes of my example, I think if minification were to make its way into the tsc, this would be desired behavior.

bryanerayner avatar Aug 19 '15 01:08 bryanerayner

@bryanerayner , your assumption is correct. The nameof operator is only used during compilation to convert type information into a string.

module pd {
   export class MyAngularControllerClass {
      public static IID : string = nameof(MyAngularControllerClass);  // "MyAngularControllerClass"
      public static $inject: string[] = [Model1.IID, Model2.IID, "$scope"];
      constructor(model1: Model1, model2:Model2, $scope:angular.IScope) {
      }
      public get nameOfThisGetter() : string {
         return nameof(this.nameOfThisGetter);    // "nameOfThisGetter";
      }
   }
   angular.module(nameof(pd)).controller(MyAngularControllerClass.IID, MyAngularControllerClass);
   // angular.module("myapp").controller("OldName", MyAngularControllerClass); < out of sync
}

Its so easy to get these hardcoded strings out-of-sync during refactoring

frodegil avatar Aug 19 '15 10:08 frodegil

This would be fantastic.

alan-compeat avatar Aug 25 '15 21:08 alan-compeat

Fantastic indeed. So much could be done with such an operator.

fredgalvao avatar Oct 05 '15 21:10 fredgalvao

We want to see how things 'feel' once #394 and #1003 land. It's possible we can solve these use cases in the type system without having to resort to adding new expression-level syntax.

In the meantime it'd be good to collect any use cases that wouldn't be adequately addressed by those proposals.

RyanCavanaugh avatar Oct 05 '15 22:10 RyanCavanaugh

Well, the case partially described by @frodegil about managing components that are registered somehow with a name (that most of the times is the same name of the Function/Class that is registered), as is the case with Angular, is a case that, as far as I can see, cannot be handled by either #394 's memberof nor by string literal types from #1003 (I'm really looking forward to the later though!).

I agree and understand how adding a new sintax element is undesired and even goes against typescript's main goal (to be a thin superset of javascript), but I still consider this proposal a very nice one.

Another small case

I use pouchdb and I make my own doc IDs, for performance and consistency reasons. These docIds are generated using a few fields, and one of them is based on the name of the model being saved, like:

For now I need to maintain a property called className on all my models:

class Person {
  className = 'Person';

  _id: string;
  $_dateCreated: number;
}

var p:Person;
p._id = `${this.className}_${window.appMetadata.cordovaUuid}__${this.$_dateCreated}__${window.uuid.v4()}`
pouchdb.put(p)

which could be turned into:

class Person {
  _id: string;
  $_dateCreated: number;
}

var p:Person;
p._id = `${nameof Person}_${window.appMetadata.cordovaUuid}__${this.$_dateCreated}__${window.uuid.v4()}`
pouchdb.put(p)

Foreseeable issues

I can see it becoming a bit harder to figure out the nameof of some things when dealing with generics or inheritance, so I will agree that this feature needs a lot of thought.

Thin alternatives

Considering that all cases that deal with property names can be handled completely by either #394 or #1003, I'd say the exposure of a getClass() and getClassName() (see example here) would solve the remaining cases I know of without needing to create new sintax elements. It could just as well be a core decorator for example.

fredgalvao avatar Oct 05 '15 23:10 fredgalvao

A use case where neither #394 , #1003 ,getClass() nor GetClassName() would help would be this in Angular2:

    @Component({
        selector: 'my-selector',
        template: `<h1>{{${nameof MyComponent.prototype.title}}}</h1>`
    })
    class MyComponent { 
        public title = "Hellow world";
    }

It would makes the code refactoring proof, but it also makes it a lot less readable, so I'm not sure if is such a good idea. Just a thought.

federico-ardila avatar Oct 29 '15 15:10 federico-ardila

Adding suggestion here to keep Enums in mind for nameof, as a shortcut for toString'ing an enum:

nameof(MyModule.Enums.FooEnum.Bar) === "Bar"

would compile to:

MyModule.Enums.FooEnum[MyModule.Enums.FooEnum.Bar] === "Bar"

or just:

"Bar" === "Bar"

kamranayub avatar Jan 13 '16 22:01 kamranayub

A good use case is for unit tests where SinonJS is used for spying/stubbing. With the proposed nameof keyword, it's possible to pass the names of the methods and properties to be spied or stubbed. When method names are refactored, the unit tests won't break because of a string that needs to be updated.

var obj = new MyClass();
sinon.stub(obj, 'methodName', () => null); // Prone to break.
var obj = new MyClass();
sinon.stub(obj, nameof(MyClass.methodName), () => null);

Or, if the stub would support to pass in a predicate to resolve the name:

var obj = new MyClass();
function stub<T>(targetObject: T, targetMethodPredicate: (T)=>string, methodStub: Function){}
sinon.stub(obj, x => nameof(x.methodName), () => null);

bgever avatar Feb 26 '16 07:02 bgever

I have a use case for constructing SQL strings. Here is a code snippet:

interface User {
    id: string;
    name: string;
    birthday: Date;
}

// Current implementation
var sql = `SELECT id,name FROM Users`;

// Desired implementation
var sql = `SELECT ${nameof(User.id)},${nameof(User.name)} FROM ${nameof(User)}s`;

The nameof() feature would make this type safe and refactor safe. For example renaming the User table to Account would be a quick refactor rather than searching through the code and missing dynamic strings like this.

I agree this should be a compile time transformation like it is in C# so we can burn in the type name.

styfle avatar Mar 11 '16 17:03 styfle

@RyanCavanaugh Five months later: #1003 has landed but doesn't help in many scenarios (see below). #394 is closed in favour of #1295. The latter seems nowhere near landing and while it solves an interesting part of the problem (typing) it doesn't help with the string/nameof part.

Maybe time to revisit?

Strings are bad because you can't "Find All References" them, you can't "Refactor/Rename" and they are prone to typos.

Some examples, using Aurelia:

let p: Person;

// Observe a property for changes
let bindingEngine: BindingEngine;
bindingEngine.observeProperty(p, 'firstName')
             .subscribe((newValue: string) => ...);

class Person {
  firstName: string;

  // Declare a function to call when value changes
  @bindable({ changeHandler: 'nameChanged'})
  lastName: string;

  nameChanged(newValue: string, oldValue: string) { ... }

  // Declare computed property dependencies
  @computedFrom('firstName', 'lastName')
  get fullName() {
    return `${firstName} ${lastName}`;
  }
}

// Declare dependencies for validation
validation.on(p)
  .ensure('firstName').isNotEmpty()
  .ensure('fullName', config => config.computedFrom(['firstName', 'lastName'])).isNotEmpty();

There you have five different APIs that would all benefit from having a nameof operator.

jods4 avatar Mar 22 '16 18:03 jods4

Valid points. I'll bring it up again (note: we're very busy right now with some upcoming work so suggestion triage is backlogged a bit)

RyanCavanaugh avatar Mar 22 '16 18:03 RyanCavanaugh

Sorry I "Ctrl-Entered" my post too soon. I have added several real-life code examples that could benefit.

To make matters more complicated, some APIs above accept paths as well. So @computedFrom('p.address.city') is valid and it would be nice to support it as well...

jods4 avatar Mar 22 '16 18:03 jods4

In this comment in another issue I proposed some kind of limited Expressions from C#.

They would be a better alternative than nameof for most of the examples in this thread:

  • They can help type the result;
  • They support more complex member accesses (nested, indexers);
  • They give you a variable to start with, which in some case you won't have in scope with nameof.

Drawback of the last point is that Expressions would not cover cases such as:

function f(x: number) {
  let s = nameof(x);
}

But that's not as common as the other use-cases.

I am copying the description of the idea from the other issue:


Assume we have a special kind of strings to denote expressions. Let's call it type Expr<T, U> = string. Where T is the starting object type and U is the result type.

Assume we could create an instance of Expr<T,U> by using a lambda that takes one parameter of type T and performs a member access on it. For example: person => person.address.city. When this happens, the whole lambda is compiled to a string containing whatever access on the parameter was, in this case: "address.city".

You can use a plain string instead, which would be seen as Expr<any, any>.

Having this special Expr type in the language enables stuff like that:

function pluck<T, U>(array: T[], prop: Expr<T, U>): U[];

let numbers = pluck([{x: 1}, {x: 2}], p => p.x);  // number[]
// compiles to:
// let numbers = pluck([..], "x");

This is basically a limited form of what Expressions are used in C# for.

jods4 avatar Mar 25 '16 12:03 jods4