Creating a union type from a string array:
const categories = [
'Category A',
'Category B'
] as const
type myCategory = typeof categories[number]
myCategory
is now 'Category A' | 'Category B'
Now, the goal is to create a discriminated union:
type categoryA = {
type: 'Category A'
// more properties
}
type categoryB = {
type: 'Category B'
// more properties
}
type selectedCategory = categoryA | categoryB
The aim here is to restrict the usage of cases in myCategory
for the discriminated union - is this achievable?
Update:
Ensuring that the cases in selectedCategory
align with the values in categories
. Currently, assigning any arbitrary string value to type
of categoryA
or categoryB
is possible
Avoiding the use of interfaces or classes.
This is being done to enable data validation and validate oneOf<myCategory>
(pseudo code) for selectedCategory
.