typing a dictionary of chocolates in typescript

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.ts
type ChocolateType = 'milk' | 'dark' | 'white';

interface Chocolate {
  brand: string;
  price: number;
  cocoaPercentage: number;
}

type ChocolateDictionary = Record<ChocolateType, Chocolate>;

const chocolates: ChocolateDictionary = {
  milk: {
    brand: 'Hershey',
    price: 2.99,
    cocoaPercentage: 30,
  },
  dark: {
    brand: 'Lindt',
    price: 4.99,
    cocoaPercentage: 70,
  },
  white: {
    brand: 'Nestle',
    price: 1.99,
    cocoaPercentage: 0,
  },
};
476 chars
28 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