There are three solutions you can use, the choice is yours based on the context.
Interface
Because a private member effectively makes it impossible for any other type to be structurally a match, you can never make an Mango look like an Apple. They do both perfectly satisfy the IFruit interface, so if you type them as IFruit they are perfectly substituatble - example below with IFruit type annotation on both new Apple(e) and new Mango(e) - although this would work with it just on Apple, for example:
interface IFruit {
getElement(): HTMLElement;
}
class Apple implements IFruit {
private _element;
constructor(element: HTMLElement) {
this._element = element;
}
getElement(): HTMLElement {
return this._element;
}
}
class Mango implements IFruit {
private _element;
constructor(element: HTMLElement) {
this._element = element;
}
getElement(): HTMLElement {
return this._element;
}
}
var e: HTMLElement;
var a: IFruit = new Apple(e);
var m: IFruit = new Mango(e);
a = m;
Inheritance
You could also solve this using inheritance. Apple and Mango could access a protected _element on the base Fruit class:
class Fruit {
protected _element : HTMLElement;
constructor(element: HTMLElement) {
this._element = element;
}
getElement(): HTMLElement {
return this._element;
}
}
class Apple extends Fruit {
constructor(element: HTMLElement) {
super(element);
}
}
class Mango extends Fruit {
constructor(element: HTMLElement) {
super(element);
}
}
var e: HTMLElement;
var a = new Apple(e);
var m = new Mango(e);
a = m;
Public
If you want to make them compatible without using the interface or inheritance, you need to make the property public:
interface IFruit {
getElement(): HTMLElement;
}
class Apple implements IFruit {
public _element;
constructor(element: HTMLElement) {
this._element = element;
}
getElement(): HTMLElement {
return this._element;
}
}
class Mango implements IFruit {
public _element;
constructor(element: HTMLElement) {
this._element = element;
}
getElement(): HTMLElement {
return this._element;
}
}
var e: HTMLElement;
var a = new Apple(e);
var m = new Mango(e);
a = m;