microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
100.83k stars 12.46k forks source link

Suggestion: A use case requires the "nameof" operator #59063

Closed IceCola97 closed 3 months ago

IceCola97 commented 4 months ago

🔍 Search Terms

"nameof" and "1579"

See also https://github.com/microsoft/TypeScript/issues/394 and https://github.com/microsoft/TypeScript/issues/1003.

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

(i know the issue #1579 and i check the issue #394 and #1003)

✅ Viability Checklist

⭐ Suggestion

Use "nameof(ISomeInterface)" instead of "ISomeInterface". Interface is a type, which means we cannot replace "nameof" by declaring a function:

function nameof(type: any): string {
    return "name" in type ? type.name : String(type);
}

...

nameof(ISomeInterface) // error

📃 Motivating Example

This is a specific example to explain why use 'nameof':

function decorator(name: string) {
    return ...;
}

interface IInterface {
    ...
}

// then we can decorate something without a literal string
// @decorator<IInterface>()
@decorator(nameof(IInterface))
class Class {
    ...
}

I hope the typescript can be written this way instead of the following:

function decorator(name: string) {
    return ...;
}

interface IInterface {
    ...
}

// this makes it more prone to errors without type checking
@decorator("IInterface")
class Class {
    ...
}

💻 Use Cases

  1. What do you want to use this for? Like the example, for decorate with an interface
  2. What shortcomings exist with current approaches? Without type checking, i dont want to write a literal string
  3. What workarounds are you using in the meantime? I'm using the literal string, a silly idea i think
MartinJohns commented 4 months ago

This could be implemented without emitting different JS based on the types of the expressions

You mistakingly checked this. Emitting additional JavaScript beyond ECMAScript support is a pretty big No-Go.

IceCola97 commented 4 months ago

This could be implemented without emitting different JS based on the types of the expressions

You mistakingly checked this. Emitting additional JavaScript beyond ECMAScript support is a pretty big No-Go.

Okay, but @decorator(nameof(IInterface)) is also a better way to write it

MartinJohns commented 3 months ago

Okay, but @decorator(nameof(IInterface)) is also a better way to write it

Which would be the exact same issue: emitting different JavaScript depending on the type.