How do you get the type of the object that is cloned from a Class Instance?

末鹿安然 提交于 2020-03-25 17:34:23

问题


assume I have this example class, but in reality it has many more properties

class Foo {
  name: string
  dob: number

  constructor(name: string, dob: number) {
    this.name = name;
    this.dob = dob;
  }

  get age() {
     return new Date().getTime() - this.dob
  }
}

Now Typescript is smart and when I instantiate the class it will give me all the right properties:

var classInstance = new Foo('name', new Date().getTime())

classInstance.name // ok
classInstance.dob // ok
classInstance.age // ok

Somewhere in my code the class gets cloned using the Spread Operator, I'm not sure what TS does behind the scene but it is really smart and gives me all the right properties

var classJSON = {...classInstance};

classJSON.name // ok
classJSON.dob // ok
classJSON.age // missing

tsplayground

This is great, however I sometime need to use the type of classJSON .. The only way I can think to extract it is to do this:

var classJSON  = {...new Foo('', 0)}
type ClassJSONType = typeof classJSON; 

Is there a way to extract the type straight out of Foo without needing Javascript to instantiate?


回答1:


It is not possible at the moment because TS type system does not allow tracking non-own properties. There is a proposal for exactly what you want. This comment also describes possible ways to express Spread operator without stripping non-own properties.



来源:https://stackoverflow.com/questions/60723614/how-do-you-get-the-type-of-the-object-that-is-cloned-from-a-class-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!