I have the following snippet that I m feeling it ugly and code repeatitive, is there any better way to achieve it more elegantly and performance freindly ?
let id : number;
if((<ParameterModel>this.activeNodeRule.node.data).parameterId){
id = (<ParameterModel>this.activeNodeRule.node.data).parameterId
}else{
id = (<RuleModel>this.activeNodeRule.node.data).parameter.parameterId
}
>Solution :
Assuming you already have a proper typing, ie this.activeNodeRule.node.data is already known to be of type ParameterModel | RuleModel at compiletime, I’d suggest to implement a type predicate. Then you can do something like the following
let data : ParameterModel | RuleModel = this.activeNodeRule.node.data;
let id = isParameterModel(data) ? data.parameterId : data.parameter.parameterId;
If you don’t have proper typing, ie the type of data is entirely unknown at compiletime, you could do as follows:
let data = this.activeNodeRule.node.data as unknown;
let id: number;
if (isParameterModel(data)) id = data.parameterId;
else if (isRuleModel(data)) id = data.parameter.parameterId;
else //do whatever needs to be done, if data is any other type.
This IMHO is the cleanest way to deal with such a situation. Good code is not always about being as short as possible, but also should be readable and understandable …