Mohammed Housseyn Taleb
Mohammed Housseyn Taleb

Reputation: 1828

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
            }

Upvotes: 0

Views: 135

Answers (4)

derpirscher
derpirscher

Reputation: 17382

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 ...

Upvotes: 3

thurasw
thurasw

Reputation: 448

What is the type of data. Is it ParameterModel | RuleModel? Does parameterId not exist on RuleModel? Assuming those two, you can do something like:

const data = this.activeNodeRule.node.data;
const id = 'parameterId' in data ? data.parameterId : data.parameter.parameterId;

Depending on your TS config, the other answers might only work if parameterId also exists on RuleModel.

Edit: Actually, if you can, do the type predicate. It's better.

Upvotes: 2

bherbruck
bherbruck

Reputation: 2226

You could do something like:

const data = this.activeNodeRule.node.data
const id = data?.parameterId ?? data?.parameter?.parameterId

This might not be type-safe depending on your context though, you may have to add a bang ! somewhere.

Upvotes: 1

Paul Dlc
Paul Dlc

Reputation: 133

If you need validate first if parameterId exists and if not asign parameter.parameterId

id = (<ParameterModel>this.activeNodeRule.node.data).parameterId?(<ParameterModel>this.activeNodeRule.node.data).parameterId:(<RuleModel>this.activeNodeRule.node.data).parameter.parameterId

if you can validate first parameter

id = (<ParameterModel>this.activeNodeRule.node.data).parameter?.parameterId

Upvotes: 1

Related Questions