ts-nameof: Recommend: Don't use this package
I now recommend not using this package or any other compiler transforms. It’s neat, but it creates code that is not portable and makes it hard to switch to new build systems. The current solutions for injecting compiler transforms are hacky and I can’t imagine the TS compiler ever supporting this out of the box.
I personally now just use the following function. It’s simple and it works for most cases… of course it’s not as featureful, but it gets you 90% of the way there.
export function nameof<TObject>(obj: TObject, key: keyof TObject): string;
export function nameof<TObject>(key: keyof TObject): string;
export function nameof(key1: any, key2?: any): any {
return key2 ?? key1;
}
Example Use
import { nameof } from "./some-relative-import";
interface SomeInterface {
someProperty: number;
}
// with types
console.log(nameof<SomeInterface>("someProperty")); // "someProperty"
// with values
const myVar: SomeInterface = { someProperty: 5 };
console.log(nameof(myVar, "someProperty")); // "someProperty"
About this issue
- Original URL
- State: open
- Created 3 years ago
- Reactions: 41
- Comments: 15 (1 by maintainers)
I published package ts-keyof. Maybe it will be useful for someone. Thanks for ts-nameof! I used it about 3 years, but now I need use esbuild and swc.
Hello everyone I know it’s been a lot of time but I just wanted to note that only recently I indeed did publish a drop-in replacement for
ts-nameof.All you have to do is remove the
@types/ts-nameofandts-nameofpackages and instead install my new “TypeScriptnameof” project as described in the project’s README.Feel free to check it out: https://github.com/typescript-nameof/nameof
Could we get some more explanation on why this is no longer recommended? It seems to me, if your environment is controllable, then the pros outway the cons.
There’s still no way to get the name of the interface itself as a string, though.
@wh1t3cAt1k I published package ts-nameof-proxy, referenced properties can be renamed by VS Code and you can try to use it.
Thank you for your candor. It would be awesome if you also write a note to this answer https://stackoverflow.com/a/33556815/1177597 when you have spare time.