nameof
for properties
I'm surprised to see three different Proxy-based answers that all allocate multiple proxies. There's no need for that performance penalty.
Simply use this:
/** nameIn<Foo>().xyz simply returns 'xyz', but lets the TypeScript compiler
* 1. check that 'xyz' is a property of Foo
* 2. rename the reference to `xyz` when Foo.xyz is renamed */
export function nameIn<T>() {
return _name_proxy as unknown as { [P in keyof T]: P };
}
const _name_proxy = new Proxy({}, { get(target, key) { return key; } });
I call it nameIn<T>
rather than nameOf<T>
because it doesn't return T
itself as a string. Example usage:
// renaming `six` (F2 in VS Code) will rename references after `nameIn`
class Class { six = 6; };
// TypeScript knows the type is "six" (even without the `: "six"`)
const nameOfIt: "six" = nameIn<Class>().six;
Arguably this is too permissive, e.g. the compiler accepts
type Anything = { [k:string]: any };
const fooName = nameIn<Anything>().foo; // inferred type: string
Here's a version that won't permit the things like that:
export function nameIn<T>() {
return _name_proxy as unknown as NamedPropsOf<{ [P in keyof T]: P }>;
}
const _name_proxy = new Proxy({}, { get(target, key) { return key; } });
// Based on "RemoveIndexSignature" from https://stackoverflow.com/a/77814151/22820
/** Keeps named properties of T, removing index props like `[k:string]: T` */
export type NamedPropsOf<T, P=PropertyKey> = {
[K in keyof T as (P extends K ? never : (K extends P ? K : never))]: T[K]
};
nameof
for classes and functions
The top answer, where nameof(console)
becomes "console"
, requires some kind of compile-time transform. However, there is a built-in JavaScript feature that works like nameof
for classes and functions:
export function Bar() {}
const barName = Bar.name;
// BTW some alternatives to this don't work if the constructor is non-public
export class Foo { private constructor() { } }
const fooName = Foo.name;
Unfortunately the type of .name
is string
rather than the actual name, but you still get the basic benefit of being able to rename the class or function without breaking your program.
Footnote: .name
gives you the name of a function, not the name of the variable that holds the function, but JavaScript has some magic to assign names on const/let/var assignments (tested in Chrome and Firefox):
// square1.name is 'square1'
const square1 = x => x*x;
// square2.name is 'square2'
const square2 = function (x) { return x*x; };
// square3.name is 'Sqr'
const square3 = function Sqr (x) { return x*x };
// square4.name is 'square2'
const square4 = square2;
Footnote: I tried this workaround, but TypeScript always infers S
as string
:
export function nameOf<T extends {name:S}, S extends string>(funcOrClass: T): S {
return funcOrClass.name;
}
const foo = nameOf(Foo); // foo: string
const bar = nameOf(Bar); // bar: string
// And even this doesn't work!
const baz = nameOf({ name: 'baz' as const }); // baz: string