samchon / typia

Super-fast/easy runtime validators and serializers via transformation
https://typia.io/
MIT License
4.64k stars 160 forks source link

Typename to string #1367

Closed Kycermann closed 2 days ago

Kycermann commented 5 days ago

Feature Request

I want to access types dynamically for networking but there are other use cases.

My request is a typia.nameOf<T> function, that simply returns the name of the type T. E.g. typia.nameOf<number>() evaluates to "number".

I could achieve something similar using typia.is but it would be O(n). My proposal would allow an O(1) implementation.

For example,

type HelloPacket = { hello: string };
type HeyPacket = { hey: string };

type Wrapper = {
  type: string;
  data: Uint8Array;
};

function sendPacket<T>(data: T) {
  typia.protobuf.encode<Wrapper>({
    type: typia.nameOf<T>(),
    data: typia.protobuf.encode<T>(data),
  });
}

function onPacket<T>(callback: (data: T) => void) {
  // packetHandlers comes from elsewhere
  packetHandlers.set(
    typia.nameOf<T>(),
    callback
  )
}

// Now a packet comes,
// I open the Wrapper where Wrapper["type"] is the name
// and call the relevant decoder made with typia.protobuf.createDecode
samchon commented 3 days ago

typia.reflect.name<YourType>().

https://typia.io/playground/?script=JYWwDg9gTgLgBDAnmYBDANHA3g1BzAZzgF84AzKCEOAIiRVRoG4AoF4AOxgFMozUAxtzgBJALLcQAI17YWcOMAAmALjgEYUTnjgAyXIQB0AMWghUMADw0ArjeU0AfKwUdUIbmo1aOeF3HxPOA4baVldeQUDAkMAFWRua3suAGYAJic9SIUYfBixTlBQyzSABkcsqOjDAFEADwEAGxsCYAA3bjFUOqKQSwBGUvLWYjZ6NEMobjJG7gEYQzcPS3FJGShHAAoASiYgA