#Generic as a string value

7 messages · Page 1 of 1 (latest)

atomic hare
#

I want to create a new type called Items, that will contain somethin like this:

type Items<TParent extends string> = {
  [`${TParent}Products`]: {
    items: ProductItems<TParent>;
    image: Image;
  };
  [`${TParent}Addons`]: {
    items: ProductItems<TParent>;
    image: Image;
  };
};

where TParent will be the name - always string - of a product category.

How can i turn TParent in to the real string value

atomic hare
#

Changing it to:

type Items<TParent extends string> = {
  [K in `${TParent}Products`]: {
    items: ProductItems<TParent>;
    image: Image;
  };
  [K in `${TParent}Addons`]: {
    items: ProductItems<TParent>;
    image: Image;
  }
};

return an error for ...Addons
"A mapped type may not declare properties or methods."

#

I have changed the type to:

type Items<TParent extends string> = Record<
  `${TParent}Products` | `${TParent}Addons`,
  {
    items: ProductItems<TParent>;
    image: Image;
  }
>;

and it is working properly - i think...
Can someone explain to me why i coudnt do it with [key: string]?

agile bay
#

the first reason is that you had the wrong syntax (you didn't write the key: part)

#

fixing that, you'll see another error:

sonic dustBOT
#
type Items<TParent extends string> = {
  [key: `${TParent}Products`]: unknown;
// ^^^
// An index signature parameter type cannot be a literal type or generic type. Consider using a mapped object type instead.
};
agile bay
#

in the end you are using a mapped type (if you look at the definition of Record you'll see it is a mapped type)