dsherret / ts-nameof

nameof in TypeScript
MIT License
492 stars 23 forks source link

Is possible to support generics? #107

Open josejulio opened 4 years ago

josejulio commented 4 years ago

I would like to know if is possible to have a way to resolve the generic name, for example:

enum MyEnum {
    A: 'a',
    B: 'b'
}

const Id = <Foo>(c: Foo[keyof Foo]) => {
    return `${nameof.resolveGeneric<Foo>()}-${c}`;
}

console.log(Id<MyEnum>(MyEnum.A));

Should print MyEnum-a; Currently nameof<Foo> prints Foo-a;

erikeckhardt commented 2 years ago

I don't think this is possible, because Id is a runtime function whose generic type parameter T could have any type argument used when called. To be done at compile-time, ts-nameof would have to build a map of every possible type that could be passed in as the type argument for Foo, emit this in code as an object or Map somewhere, then make the Id function consult that emitted Map. That's not even possible, and it's not what the point of nameof is, which is to super-lightly replace the nameof() expression with a literal string in the raw JavaScript.

nameof() is all about compile-time literals.

I'm no expert in nameof, but, what happens if you do `${nameof<MyEnum>()}-${nameof<MyEnum>(o => o.A)}`?