1

I have the following base class:

export default class BaseModel{
    Id:string;
    CreatedDate:Date;
}

With following child class:

export default class ProfileModel extends BaseModel{
    UserName:string;
    Email:string;
    Password:string;
    FirstName:string;
    LastName:string;
    Vendor:Boolean;
    Authenticated:Boolean;
    constructor(aUserName, anEmail, aPassword, aFirstName, aLastName, 
aVendor, isAuthenticated){
    super();
    this.UserName = aUserName;
    this.Email = anEmail;
    this.Password = aPassword;
    this.FirstName = aFirstName;
    this.LastName = aLastName;
    this.Vendor = aVendor;
    this.Authenticated = isAuthenticated;
    }
    public static NewNonVendor(aUserName, anEmail, aPassword, aFirstName, 
aLastName):ProfileModel{
        return new ProfileModel(aUserName, anEmail, aPassword, aFirstName, 
    aLastName, null, false);
    }
}

I would like to move the fromJSON method to base class to handle serialization for all child classes. I want to basically do the following but having trouble coming up with the correct syntax:

export default class BaseModel<T>{
    Id:string;
    CreatedDate:Date;
    static fromJSON(d: Object): T {
        return Object.assign(new T(), d);
    }
}

1 Answer 1

1

If you type the T generic as T extends BaseModel, you can type the this for the static method as this: new () => T:

class BaseModel {
  Id: string;
  CreatedDate: Date;
  static fromJSON<T extends BaseModel>(this: new () => T, d: Object): T {
    return Object.assign(new this(), d);
  }
  constructor(Id: string, CreatedDate: Date) {
    this.Id = Id;
    this.CreatedDate = CreatedDate;
  }
}
Sign up to request clarification or add additional context in comments.

9 Comments

@CeertainPerformance Yes this appears to work. Was there a reason you added the constructor?
Only so that the TypeScript would compile properly on the playground without errors (use your original constructor implementation, of course - it isn't in the question, so it was throwing a TS error)
so now when trying to call fromJSON using following: let test = ProfileModel.fromJSON(json as Object); I get following error: The 'this' context of type 'typeof ProfileModel' is not assignable to method's 'this' of type 'new () => ProfileModel'.
It looks to compile without errors here: typescriptlang.org/play?#code/…
Also note that JSON is a way of representing an object in a string. If what you have is an object, it's not a JSON - maybe call it fromPlainObject instead of fromJSON? Or pass in the JSON and use JSON.parse on it inside the method?
|

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.