Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a simpler way to write this on one line in TypeScript?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 …

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading