In a very specific scenario, the body of type varies based on the length_type attribute (as illustrated in the example).
enum LengthTypeEnum {
SELECT = 'SELECT',
STATIC = 'STATIC',
CONDITION = 'CONDITION',
PERIOD = 'PERIOD'
}
type LengthType<T extends LengthTypeEnum> =
T extends LengthTypeEnum.SELECT ? { length_type: T, lengths: number[] } :
T extends LengthTypeEnum.PERIOD ? { length_type: T, length_min: number; length_max: number }:
T extends LengthTypeEnum.STATIC ? { length_type: T, length: number }:
T extends LengthTypeEnum.CONDITION ? { length_type: T, conditions: any[] }:
{}
;
let variableLength: LengthType<LengthTypeEnum> | null = null
function handleSelect(length_type: LengthTypeEnum):void{
variableLength = initializeLengthData(length_type)
}
function initializeLengthData<T extends LengthTypeEnum>(length_type: T):LengthType<T>{
if(length_type === LengthTypeEnum.SELECT){
return {length_type: length_type, lengths: []} as any as LengthType<T>
}else if(length_type === LengthTypeEnum.PERIOD){
return {length_type: length_type, length_min:0, length_max: 0} as any as LengthType<T>
}else if(length_type === LengthTypeEnum.STATIC){
return {length_type: length_type,length: 0} as any as LengthType<T>
}else if(length_type === LengthTypeEnum.CONDITION){
return {length_type: length_type,conditions: []} as any as LengthType<T>
}
return {} as LengthType<T> ;
}
The "Length Type" type functions correctly. Once I check the length_type value, the compiler can infer the structure of the rest of the variable.
However, there is an issue with initializing the variable when choosing the length_type. The code works but it relies heavily on using "as any" type casting which does not look elegant. Is there a way to avoid this or should I consider a different approach?
Minimal reproducible version in GUI example playground
Minimal reproducible version in Typescript only playground