问题
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