3

I wish to get the name of a type as shown in the example below.
Can it be achieved ?

type Type = 1

type TypeName <T> = `Type name is ${T & string}`

type NameOfType = TypeName <Type> // never, expected 'Type name is Type'

playground link

zedryas
  • 718
  • 6
  • 19
  • 2
    Not possible to get type names in the type system – Titian Cernicova-Dragomir Feb 08 '22 at 10:30
  • thanks for the reply - those names must be stored somewhere - could it be a feature request to make them available ? Or it does not make sens @TitianCernicova-Dragomir? My use case is a test type system where I wish to inform user that type tested to be (for instance equal) is not - I can do that but can only hint ("Types are not equals") and being able to hint ("Type A is not type B") would much more useful – zedryas Feb 08 '22 at 10:45
  • 1
    I seem to remember proposals for `nameof` similar to C#, but I don't think there was much enthusiasm for adding it. TS has `keyof` and that seems sufficient for most use cases for now. – Titian Cernicova-Dragomir Feb 08 '22 at 10:47
  • yep I've seen the `nameof` but if I remember correctly it was more of a runtime tool - on the other hand `keyof` does not serve the same purpose at all – zedryas Feb 08 '22 at 10:49
  • You can make a map of types. See here an [example](https://tsplay.dev/NBjQpN). However, it is only a workaround – captain-yossarian from Ukraine Feb 08 '22 at 11:25
  • hi @captain-yossarian the link you provide is the same as the playground I've provided ... sure u've posted the correct link ?? – zedryas Feb 08 '22 at 14:57
  • 1
    @zedryas please try again, I'm 100% sure. Here you have [another one](https://tsplay.dev/WKVvom) – captain-yossarian from Ukraine Feb 08 '22 at 15:05
  • something wrong with my computer lol when I try to open your link with a incognito window it lead's me to the base typescript playground page, and when in not incognito I land on the playground I've posted earlier. Dunno what's going on :/ could you post it elsewhere ? (if not too much to ask sorry about the strange request) – zedryas Feb 08 '22 at 16:04
  • 1
    Got it working on chrome - did bug on Safari don't know why please ignore my last comment and thanks a lot – zedryas Feb 08 '22 at 16:05

1 Answers1

-1

You can't do that. TypeScrip is just an extortion of JavaScript. Where are no types and generics in runtime. Types exist only in context of TypeScript.

Your question is similar to this one. How to get Generic class<T> name of typescript?

  • 6
    That's not the reason. This is not a runtime question, but a typing question. – Matthieu Riegler Feb 08 '22 at 10:34
  • 1
    yep it's not for runtime - the aim is to provide informations on misuses of types in some cases where It's possible -and it's only for the ts compiler no need for it in js – zedryas Feb 08 '22 at 10:43
  • https://stackoverflow.com/a/57594451/470749 might be the answer I'm looking for. – Ryan Jun 07 '22 at 14:41