0

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.

3
  • 1
    as IAddressModel does 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. Commented Jan 3, 2018 at 11:21
  • 1
    Possible duplicate of Angular: Typescript casting JSON response as object model not working Commented Jan 3, 2018 at 11:23
  • You did not present any initialization code for user and user.Address in your code. In case you did not instantiate user.Address you should not expect it to be set, hence it will be undefined Commented Feb 14, 2019 at 8:08

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.