Issue
I have a class with a constructor that returns a complex object who's type is partly inferred. Now I want to add some properties to that returned type. I don't want to declare them on the class. Is there a way to do this?
type AdditionalProps = {
myAdditionalProp : string
}
const myInstance: inferredType & AdditionalProps = new MyClass()
myInstance.myAdditionalProp = "I love typescript."
Solution
You can use Object.assign
to add new props to newly created object.
The type is inferred correctly, but can be stated explicitly as well.
class MyClass {
id: number;
constructor() {
this.id = 1;
}
}
type AdditionalProps = {
myAdditionalProp : string
}
const myInstance: MyClass & AdditionalProps = Object.assign(new MyClass(), {myAdditionalProp: 'I love typescript.'});
// NOTE: the type can be inferred
console.log(myInstance.id);
console.log(myInstance.myAdditionalProp);
Answered By - Lesiak
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.