dsherret / ts-nameof

nameof in TypeScript
MIT License
492 stars 23 forks source link

make return type a unary union type #96

Closed Floby closed 4 years ago

Floby commented 4 years ago

I don't know if it is even possible given the current state of the typescript transformation pipeline but my suggestion would be that the return value of the nameof functions be of a stricter type than string.

For example :

// Current behaviour
let identifier: "MyThing"
identifier = nameof<MyThing>() ///> error TS2322: Type 'string' is not assignable to type '"MyThing"'

// Desired behaviour
let identifier: "MyThing"
identifier = nameof<MyThing>() /// checks out
identifier = nameof<MyOtherThing>() ///> error TS2322: Type '"MyOtherTHing"' is not assignable to type '"MyThing"'

After a while of reading, It seems transforms happens after the type checker does its thing, so I'm not even sure this is possible outside of typescript itself.

dsherret commented 4 years ago

@Floby I wish, but yes you're right that it happens after the type checker (AST Parsing -> Type Checking -> [ts-nameof works here]Transformation). It is possible to get this working, but it would require injecting into both the language service and a pre-type checking transform. Basically it would be a lot of work and require a lot more setup for people. For now, I'm going to mark this as "won't do", but in the future it might be something that would be more feasible. Definitely would be nice!

Floby commented 4 years ago

Fair enough =)