category
is a classification you define as a reference. In the case of your C
example, if you execute the following snippet:
const myItem:ItemCategory = itemFromList();
Object.entries(myItem).map(itemValue => { /* 'itemValue' can be either a 'string' or 'number' */ });
It is more advisable compared to example B, where itemValue
would be of type any
, which is a mystery in the world of TypeScript.
When you specify a category, you are defining a range of possible values that can be assigned. Depending on the usage of modify()
, you can implement different category strategies.
If you are certain that the object will strictly adhere to {label:string, quantity:number}
then you should define your category accordingly:
type Item = { label:string; quantity:number };
If you only know that object properties may contain either a string or a number, then you can define a category similar to your example, but utilizing a Dictionary
:
type ItemCategory = Dictionary<string, string | number>;
Lastly, if you are unsure about the type held within an object, I suggest a slight adjustment by using uncertain
type ItemCategory = Dictionary<string, uncertain>;
Assigning to object
will tag any property value as any
, providing no safeguarding of types. Utilizing uncertain
offers a slightly better level of type protection, a topic that can be explored further. Resources discussing the advantages of selecting uncertain
over any
are readily available.