jeudi 23 novembre 2023

How can I convert a TS Type/Interface into an object with the keys for that type and the primitives it's made of?

Explanation with an example:

I have the following TS interfaces/types:

interface Stock {
    name: string;
    value: number;
}

type Account = {
    username: string;
    portfolio: Stock[];
}

I now want to have some magic function to turn the Account type into an object like this:

{
  username: {
    type: 'string',
  },
  portfolio: {
    type: 'array',
    items: {
      type: 'object',
      properties: {
        name: {
          type: 'string',
        },
        value: {
          type: 'number',
        },
      },
    },
  },
}

This might be asking for too much since 'array' is not a JS primitive, so maybe that should be 'object' instead - but I hope this gets the idea across.

Very important to note where is that I don't nessecarily have an object that conforms to this type in runtime - I only have the interface/type - no objects to actually go through.

I believe this topic is related to reflection, but any ideas on how to achieve something like this would be appreciated.

The idea is to be able to do this in runtime which is where the trouble comes from. I want to generate an AST from the interfaces/types and have it recursively travel all the interfaces/types that are being used by all the libraries.





Aucun commentaire:

Enregistrer un commentaire