Issue
I have an interface in that interface there is a property called data
which is an array.
So looks something like this:
type Data = { prop1: string; prop2: string }[];
interface MyInterface {
prop1: string;
data: Data;
}
Now I have an RxJS stream,
In that stream, the interface is MyInterface
.
So now I want to display something slightly different in the data property. So what I did was Extend add a new value
type DataExtended = Data & {
newValue: string
}
Add that new type to an extended interface
interface MyInterfaceExtended extends MyInterface {
data: DataExtended
}
Now in the controller, I call a service that has an HTTP service that has MyInterface
as the expected result. But I need to change that data structure, so I have the following:
var myData$ = Observable<MyInterfaceExtended>;
constructor(private myService:myservice){
this.myData$ = this.myService.get().pipe((map(value)) => {
foreach(value.data, (data) =>{
data.newValue = 'new';
})
return value
})
}
But I keep getting the error that says:
'newValue' does not exist on type {etc}
Why would that be?
Solution
Assumption:
Assume that the this.myService.get()
returns Observable<MyInterface>
.
There is an issue with the DataExtended
type, as you combine the Data
which is an array of { prop1: string; prop2: string }
type with an object { newValue: string }
.
The correct type should be:
type DataExtended = Data &
{
newValue: string;
}[];
for existing types.
Or you should define the Data
as a single object rather than an array type.
New types:
type Data = { prop1: string; prop2: string };
interface MyInterface {
prop1: string;
data: Data[];
}
type DataExtended = Data &
{
newValue: string;
};
interface MyInterfaceExtended extends MyInterface {
data: DataExtended[];
}
For converting the data with the map
RxJS operator, you can achieve with:
Solution 1 with existing types:
this.myData$ = this.myService.get()
.pipe(
map((response: any) => {
let newResponse: MyInterfaceExtended = response;
newResponse.data = newResponse.data.map((x) => ({
...x,
newValue: 'new',
}));
return newResponse;
})
);
Solution 2 with the new types:
this.myData$ = this.myService.get()
.pipe(
map(
(response: any) =>
({
data: response.data.map(
(x: Data) =>
({
...x,
newValue: 'new',
} as DataExtended)
),
} as MyInterfaceExtended)
)
);
Answered By - Yong Shun
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.