I have a typescript interface that I am trying to extend, but at run time my properties and methods are missing. Could someone have a look and see if there is something I'm doing completely wrong?
Inherited Interface generated from TypeLite
declare module ModelsShared {
interface AddressModel {
Country: ModelsSupportingData.SupportingDataModel;
County: string;
Line1: string;
Line2: string;
Line3: string;
Postcode: string;
Town: string;
}
}
As I can't change these interfaces as they are automatically re-generated, I extended it with my own interface:
interface IAddressModel extends ModelsShared.AddressModel {
FlatString: string;
asFlatString() : string;
}
And then implemented that interface with an exported class:
export class AddressModel implements IAddressModel {
public Country: ModelsSupportingData.SupportingDataModel;
public County: string;
public Line1: string;
public Line2: string;
public Line3: string;
public Postcode: string;
public Town: string;
public FlatString : string;
public asFlatString = (): string => {
return "A nice formatted address";
}
}
However, even on casting the address as my interface, such as:
let address: IAddressModel = (user.Address as IAddressModel);
And although VS is happy, I do not get the property or method at run-time, I just undefined.
as IAddressModeldoes not do any casting or conversion. It's an assertion; you're telling the compiler you know it will be that type. In this case, it seems you're wrong. Presumably you're getting JSON somewhere; you need to explicitly deserialise that into the appropriate class.useranduser.Addressin your code. In case you did not instantiateuser.Addressyou should not expect it to be set, hence it will beundefined