Force every value of union type in an array

Let's say that I had the following union type:
type Name = "John" | "Sean" | "Theo";
type Name = "John" | "Sean" | "Theo";
If I wanted to have an array that accepted a list of those values I would do something like this
const names: Name[] = ["John", "Sean"];
const names: Name[] = ["John", "Sean"];
Is there a way to force an error if the array doesn't contain all the values?
15 Replies
Samathingamajig
the only way I know how to achieve what you want is to do the reverse:
const names = ["John", "Sean", "Theo"] as const;
type Name = typeof names[number];
const names = ["John", "Sean", "Theo"] as const;
type Name = typeof names[number];
Samathingamajig
i just googled it and found the answer you're looking for: https://stackoverflow.com/a/60132060/12101554
Stack Overflow
Make sure array has all types from a union
Say I have a union that looks like this type Colors = 'red' | 'blue' | 'pink' Is it possible to type check an array against this union and make sure the array contains all of the types? I.e.: ...
Samathingamajig
i searched "typescript make array contain all values of a union"
sean
seanOP2y ago
I'm reconsidering my google skills since I googled it for the past 40 minutes Thank you tho! Now that I think about it I've been using duckduckgo for a week
Pieter
Pieter2y ago
It would be cool if you could encapsulate this in a type, I am struggling with the notation
Samathingamajig
on ddg it's the second result
sean
seanOP2y ago
I should ditch this job Going farming Anyhow, thank you once again @Samathingamajig , have a good rest of your day/night!
Samathingamajig
angular carrot farmer
sean
seanOP2y ago
don't tell me that I got hired to code in vue, which means I now don't deserve to enter the react church anymore
Samathingamajig
i have to use google since i dont want to switch back and forth every day because my school blocks all search engines excep tgoogle
sean
seanOP2y ago
why would anyone do that that's one of the dumbest things I've ever heard
Samathingamajig
sometimes you need to put it in a function, but it boils down to a no-op at runtime (and typescript might even get rid of it all together) since it's just an identity function (returns the input with no extra operations, always)
Samathingamajig
looks like it doesn't get compiled away
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
sean
seanOP2y ago
How would you guys imagine this feature if it actually existed and didn't need those 3 lines of boilerplate Hahahah it depends on the day, yesterday I felt godly Luckily I'm shutting everything down in a bit since I'm almost done
Want results from more Discord servers?
Add your server