Matthias Falk
1 min readOct 1, 2024

--

"No more manually typing out every single value." is not true since you define

const fruits = ["apple", "banana", "orange", "mango"] as const;

That is, you have to type out in fact every single value within the array. However, I appreciate the idea of a single source of truth. Your idea can be extended into avoiding string literals for this purpose at all. OK, but why? Imagine, you decide later on to change "apple" to "Apple". Then you have to search your code base for the string literal "apple". The point is, at some locations this string literal in fact might be used as member of type Fruits. There you have to substitute it. At other locations it might serve other purposes (e.g. being a part of some text). There you must not change it. Thus, you have to check every occurrence of "apple", no automated replacement is possible (in the general case).

So, how to avoid string literals for this purpose?

enum FruitsEnum {apple, banana, orange, mango};

type Fruits = keyof typeof FruitsEnum // "apple" | "banana" | "orange" | "mango"

Wherever you want to use "apple" as member of type Fruits, say you want it assign to a variable "someFruit", do it like this:

const someFruit = FruitsEnum[FruitsEnum.apple];

If you now want to change "apple" to "Apple" just perform a rename refactorization for the member apple of FruitsEnum to Apple within your IDE. The point is that renaming support exists only for identifiers, not for strings.

--

--

No responses yet