I'm currently exploring typescript and facing a challenge with dynamically assigning values to a union type:
type Labs = (name === 'dakota') ? 'fruit' | 'veg' : 'plow' | 'field' | 'till';
An error keeps popping up stating that "name refers to a value but is being used as a type".
To clarify, my goal is to restrict the valid values of type Lab
:
type Labs = 'fruit' | 'veg'
// if name === 'dakota', otherwise:
type Labs = 'plow' | 'field' | 'till'
I've attempted using a function that will return the correct type:
function getLabType<Type>(arg: string): Type {
if (arg === 'dakota') {
type A = 'fruit' | 'veg';
return A
}
type B = 'plow' | 'field' | 'till'
return B
}
type Lab = getLabType('dakota')
However, I am encountering a similar warning about A
and B
only referring to types but being used as values.
If you have any insights on how I can conditionally set values for a union type, I would greatly appreciate your help.