DEV Community

Discussion on: We don't have to use Enums on TypeScript? 【Discussion】

Collapse
peerreynders profile image
peerreynders • Edited on

We start with

const bigTechz = {
  Google: 'Google',
  Apple: 'Apple',
  Amazon: 'Amazon',
  Facebook: 'Facebook',
} as const;
Enter fullscreen mode Exit fullscreen mode

Then 2021-10-28

const bigTechz = {
  Google: 'Google',
  Apple: 'Apple',
  Amazon: 'Amazon',
  Facebook: 'Meta',
} as const;
Enter fullscreen mode Exit fullscreen mode

No need to change bigTechz.Facebook anywhere in your code and more importantly in code you don't control (but that uses your code).

With

type BigTechz = "Google" | "Apple" | "Amazon" | "Facebook";
Enter fullscreen mode Exit fullscreen mode

the literal values are used in the source code itself. So

  • either update all occurrences of "Facebook" in the source code; impossible if it is used in code you don't control.
  • or just leave it as is and hope nobody complains that it should be "Meta", not "Facebook".

Trade-offs ...


Added bonus: iterability

const allBigTechz = Object.values(bigTechz);

// Using type predicates
// https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates
//
function isBigTechz(name: string): name is BigTechz {
  return (allBigTechz as string[]).includes(name);
}

const myFav = bigTechz.Apple;
console.log(isBigTechz(myFav)); // true
console.log(isBigTechz('Walmart')); // false

const formatter = new Intl.ListFormat('en', {
  style: 'long',
  type: 'conjunction',
});
console.log(`The BigTechz: ${formatter.format(allBigTechz)}`); 
// "The BigTechz: Google, Apple, Amazon, and Meta"
Enter fullscreen mode Exit fullscreen mode
Thread Thread
taishi profile image
Taishi Author

Thanks @peerreynders !

No need to change bigTechz.Facebook anywhere in your code and more importantly in code you don't control (but that uses your code).

Good point!
iterability can be a big plus.
Now your method is starting to look handy! Thank you!