My Typescript Class contains the method getProductAttributeByName(name: string) which filters the collection defined as parameter of the constructor.
class Product {
id: string;
constructor(productDto: IProductDto) {
this.id = productDto.id;
}
getProductAttributeByName(name: string): ProductAttribute {
// I need productDto (the constructor parameter) here:
return productDto.productAttributes.filter(x => x.name === name)
}
}
This is not allowed, so currently I'm doing:
class Product {
id: string;
productDto: IProductDto;
constructor(productDto: IProductDto) {
this.id = productDto.id;
this.productDto = productDto;
}
getProductAttributeByName(name: string): ProductAttribute {
return this.productDto.productAttributes.filter(x => x.name === name)
}
}
Needless to say that this is terrible. I'm exposing a public property which is only needed inside a method, for the only reason that I cannot access the constructor parameter. I also tried, out of desperation, to declare the property as private, like this:
class Product {
id: string;
private productDto: IProductDto;
constructor(productDto: IProductDto) {
this.id = productDto.id;
this.productDto = productDto;
}
getProductAttributeByName(name: string): ProductAttribute {
return this.productDto.productAttributes.filter(x => x.name === name)
}
}
But this doesn't change the fact that the property is still accessible once the object has been initialized:
var product = new Product(myDto);
// product.productDto is accessible!
Is there a way to access a constructor parameter inside a method without having to declare a property that will be publicly accessible?