I want to change how object is filled with properties.
Currently I have
export interface INewOffer {
employment?: IEmployment;
heightWeight?: IHeightWeight;
}
export interface IEmployment{
trainings?: string;
activeEmployment?: string;
wage?: string;
}
And function which creates an object looks like this:
private dataGenerator(newCustomer: INewCustomer): INewOffer {
const data: INewOffer = {};
if (NullCheck.isDefinedOrNonNull(newCustomer.age)) {
data.employment = {
trainings: newCustomer.trainings,
activeEmployment: newCustomer.activeEmployment,
wage: newCustomer.wage,
};
} else {
data.employment = {
wage: newCustomer.wage,
};
}
data.heightWeight = {
height: '180',
weight: '75',
};
return data;
}
I have tried to change my code to
private dataGenerator(newCustomer: INewCustomer): INewOffer {
const data: INewOffer = {};
if (NullCheck.isDefinedOrNonNull(newCustomer.age)) {
data.employment.trainings = newCustomer.trainings;
data.employment.activeEmployment = newCustomer.activeEmployment;
data.employment.wage = newCustomer.wage
} else {
data.employment.wage = newCustomer.wage
}
data.heightWeight.height = '180';
data.heightWeight.weight = '75';
return data;
}
and VS code IDE does not see any issues e.g: when I mouse over the:
data.
it saysconst data: INewOffer
employment.
=>(property) INewOffer.employment?: IEmployment
wage
=>(property) IEmployment.wage?: string
but when I run test I have error:
E/launcher - Error: TypeError: Cannot set property 'wage' of undefined
I have tried setting it like:
data.employment!.wage = newCustomer.wage
but it does not work. Then I have found out that there is no support in typescript for Optional Chaining.
and my question is, why IDE does not says its an error? or maybe I have to do something else to make it work?