dsherret / ts-nameof

nameof in TypeScript
MIT License
493 stars 23 forks source link

In nameof<T>(func?) It does not work if func is passed as a parameter. #87

Closed kvvinokurov closed 5 years ago

kvvinokurov commented 5 years ago

protected GetControlProps2(property: (obj: M) => void): IPropsEditable { let propertyName = nameof<M>(property); return this.GetControlProps(propertyName); } console.log(propertyName) -> 'property'

dsherret commented 5 years ago

Yeah, that makes sense. It throws an error, right?

dsherret commented 5 years ago

Say there is code like so...

export function doNameof(func: (obj: M) => unknown) {
    console.log("hello");
    return nameof<M>(func);
}

doNameof(obj => obj.something);

I'm guessing your expected compiler transform behaviour is as such:

export function doNameof(name) {
    console.log("hello");
    return name;
}

doNameof("something");

There are multiple problems here:

  1. The compiler won't necessarily have control to be able to transform calls to doNameof. For example, the call might be done in a different library or in code the compiler isn't compiling.
  2. If this scenario was supported it would blow up the complexity of the library. The library would have to follow the call graph to make the doNameof call act like a transform... I'm imagining implementing this and it would be quite complex.

So basically, this is working as intended. Let me know if you need any clarifications on this.

kvvinokurov commented 5 years ago

Yes, absolutely right.

For example, in the alternative package ts-simple-nameof works, BUT only in dev mode webpack

dsherret commented 5 years ago

That library is a runtime solution to the problem that will work as long as the code is not minified and not in the type domain. Take a look at its source: https://github.com/IRCraziestTaxi/ts-simple-nameof/blob/master/src/nameof.ts

This library is a compile time solution and only transforms nameof call sites since transforming transitive call sites would be impossible to do since those call sites wouldn't necessarily be within the code being transformed. It would also be very slow and difficult to implement that.

Anyway, closing this because this is by design.