kontent-ai / model-generator-js

MIT License
13 stars 9 forks source link

Use a string literal for type codename in the types for items generated in the content-types folder #49

Closed JiriLojda closed 1 week ago

JiriLojda commented 7 months ago

Motivation

Imagine you have content types Product and Page. The model generator generates types Product and Page in their respective files in the content-types folder. The types are of shape IContentItem<...> so they have specific elements defined based on their type. However, the type of the type property is a simple string while it is obvious that the type Product can only have the value product in the type field. It would make working with the types safer and easier if the types would have the precise string literal assigned to the type property. For example:

const renderPageOrProduct = (item: Product | Page) => {
  switch (item.system.type) {
    case contentTypes.product.codename:
      // with the current model generator, TS doesn't know that in this case the type of item is Product instead of the general Product | Page
      // if the codename property would have an exact type, TS would be able to infer that and we would not be forced to unsafely cast it to the expected type
    case contentTypes.page.codename:
      // ...
  }
};

Proposed solution

Assign the exact string literal to the type property. It would require to either extend the IContentItem type to accept another generic parameter or you can modify the type in the generated file. (e.g. IContentType<...> & { system: { type: "product" } })

Enngage commented 1 week ago

Implemented in the next major version of the generator.