I'm using 3rd party library (library for communicating with Commerce tools, but that does not matter).
I have a function that returns a Category, but the issue here is that category can have a custom field that is not accounted in the type provided with said library. So when I'm trying to do something like this:
const getCategory = (): Category => {
return {/* ... */}
}
const myField: string = 'my-field';
const categoryOrginal = getCategory();
const orignalField = categoryOrginal.custom[myField]; // does not work - TS complains
Typescript throws an error:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'CustomFieldsType'.
No index signature with a parameter of type 'string' was found on type 'CustomFieldsType'.(7053)
So I have some string variable with a name of my field, but I can not index into the category, because the type does not include such possibility (even though in reallity the object itself has that field).
What I'm trying to do it to provide my own new type, that I could assign to category, in which I could extend the type to include additional fields:
type ExtendedCustomFieldsType = CustomFieldsType & Record<string, string>;
type ExtendedCategory = Omit<Category, 'custom'> & {
custom?: Maybe<ExtendedCustomFieldsType>;
};
const categoryTest: ExtendedCategory = getCategory(); // error
This way I should be able to index using any string and the error should go away. But it is not the case I have a another weird error.