I am new to Typescript and Javascript. I have written the following piece of code which works fine. I want to understand which is good and recommended to use in Typescript. Let me explain a bit. When we pass more than 4 parameters lets say 8 parameters, sonar complains. So we create an object and populate all the required fields and pass to a function and we get the result. We can also define all the fields inside curly braces like this given below.
const pType: any = {firstName: "John", lastName: "Abraham"};
At the same time, we can define a class like this.
export class Person {
private _firstName: string = "";
private _lastName: string = "";
// All get set methods/functions
}
Please help me to understand the difference between the above two, which is better and why in terms of memoray usage. I have written the sample class for simplicity.
export class PassNReturnMultipleParams {
public getAddress_Type1(person: Person): Address {
console.log("First Name: ", person.firstName);
// write logic to validate
const address: Address = new Address();
address.cityName = "Bangalore";
address.flatName = "#123";
address.streetName = "Richmond Road";
return address;
}
public getAddress_Type2(pType: any): any {
console.log("First Name: ", pType.firstName);
// write logic to validate
const adrsType: any = {cityName: "Bangalore", flatName: "#123", streetName: "Richmond Road"};
return adrsType;
}
public check_Type1() {
const person: Person = new Person();
person.firstName = "John";
// Set other values
const adrs: Address = this.getAddress_Type1(person);
console.log("Address City Name: ", adrs.cityName);
}
public check_Type2() {
const pType: any = {firstName: "John", lastName: "Abraham"};
// Set other values
const adrs: any = this.getAddress_Type2(pType);
console.log("Address City Name: ", adrs.cityName);
}
}
const test: PassNReturnMultipleParams = new PassNReturnMultipleParams();
test.check_Type1();
test.check_Type2();
In the above class, there are two functions getAddress_Type1() and getAddress_Type2(), which one is always recommended in Javascript, Typescript world. Both work fine for me.