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

Time:06-11

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
            }

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

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.

  • Related