To type a dictionary of chocolates in TypeScript, you can make use of TypeScript's "Record" utility type. This type allows you to define an object that has keys of a specific type and corresponding values of another type.
Here's an example of how to define a chocolate dictionary:
index.ts476 chars28 lines
In this example, we define the ChocolateType
as a union of three strings that represent the chocolate types. We also create an interface
for chocolates that defines their properties: brand, price and cocoaPercentage.
Next, we define the ChocolateDictionary
type using Record
with the ChocolateType
as the keys, and Chocolate
as the values.
Finally, we create an instance of the ChocolateDictionary
using an object literal and assign it to the chocolates
constant.
With this setup, TypeScript will ensure that the keys of the dictionary are only the defined ChocolateType
, and that the values are always Chocolate
objects with the required properties.
gistlibby LogSnag