0

I am writing a code that handles classes instantiation (unmarshaller).

First, I create an object. I do that using let obj = new BaseModel.
During processing of the input data, I eventually figure out the class of the unmarshalled object.
I have that class, in terms of <T extends BaseModel> clazz : { new (): T }.

Now I would like to change the class of the object created earlier, in a way that it doesn't collide with TypeScripts class handling code.

Is this the right way?

Object.getPrototypeOf(result).constructor = clazz;

Edit: This is not it. While the property value stays, the browsers console still show the type used with new.

Or perhaps is there a construct in TypeScript that would do this in more future-compatible way?

2 Answers 2

0

Or perhaps is there a construct in TypeScript that would do this in more future-compatible way?

This is right. You use constructor to determine the creating function in TypeScript just like you do in JavaScript.

Sign up to request clarification or add additional context in comments.

1 Comment

Could you please add some example? Say want to assign MyClass to be the class of an existing object.
0

If I understand your question correctly, you want to change the type of an object at runtime from the type you created with new to another, possibly derived, type.

I think you would be better off instantiating an instance of the class you want and then copying the members of the other object into it.

If you don't want to run the constructor, you could do the following with jQuery:

let newTypeObj:NewType = $.extend(true, Object.create(NewType.prototype), oldTypeObj);

If you want to run the constructor for the new type before merging you can do:

let newTypeObj:NewType = new NewType();
$.extend(true, newTypeObj, oldTypeObj);

If you don't have or don't want to use jQuery then you can write a function in your new type that takes an instance of the old type and copies the members or write a generic extend using vanilla JavaScript.

This question has a bit more about alternatives but the general consensus seems to be that you can't change an object's class: Changing an Object's Type in JavaScript

Comments

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.