Typescript object casting not working

I have an HTTP API. I am loading a set of objects as json.

I want to pass a Typescript object, but with the keyword “how” it does not work and not even with the <Type> in front of the object.

r.forEach(entry => { entry.creationDate = new Date(entry.creationDate.date); entry.creator = <User>entry.creator; return entry; }); 

The .log console immediately after entering entry.creator displays the usual "object".

Can someone give me some advice?

+5
source share
2 answers

I struggled with similar problems, and, in my opinion, this is a defect in typescript. When you do actors, so do you. Or an example code:

 class User { name: string; doConsole(): void { console.log(`Name: ${this.name}`); } } let userObj = { name: 'jose' }; let user = new User(); Object.assign(user, userObj); user.doConsole(); 

You will notice that doConsole will not be a function in a cast object. This is the generated JS:

 var User = (function () { function User(name) { this.name = name; } User.prototype.doConsole = function () { console.log("Name: " + this.name); }; return User; }()); var userObj = { name: 'jose' }; var user = userObj; user.doConsole(); 

As you can see, it does not use the prototype function that you prepared the class when performing the translation. My alternative was to do something like this:

  class User { name: string; doConsole(): void { console.log(`Name: ${this.name}`); } } let userObj = { name: 'jose' }; let user = new User(); Object.assign(user, userObj); user.doConsole(); 

This ensures that you use the prototype function, as you can see the generated JS:

 var User = (function () { function User() { } User.prototype.doConsole = function () { console.log("Name: " + this.name); }; return User; }()); var userObj = { name: 'jose' }; var user = new User(); Object.assign(user, userObj); user.doConsole(); 

So basically, I say that I agree with you that it should work the way you do, but the transpiler does not use the prototyped function, so it will not work.

Hope this helps you.

+11
source

Javascript itself does not support strong typing. You can use strong printing only with Typescript, but it only works at compile time. Expected runtime behavior. Not a mistake or mistake with your code.

Some of the great features provided by Typescript are:

  • Check compilation time: look for potential errors in the code before the client.
  • Strongly typed objects: By specifying the type of objects, your functions expect that you can reduce the risk of unexpected results.

The source of my quote and more information on strong typing is here .

+4
source

Source: https://habr.com/ru/post/1258265/


All Articles