How do you handle a request with uncertain data and type checking?
For instance, if you are making an HTTP call to an API where various data can be returned, but your component requires a specific data structure defined by an interface.
Here's a simpler example. Answer the question for this example as well!
export interface IComponentData {
copy1: string;
total: string;
}
/* ----- */
componentCopy: IComponentData; // component data
componentCopyLoaded(data: { status: string; data: IComponentData }): void {
if (data.status === 'error') {
this.isError = true;
} else if (data.status === 'success') {
this.componentCopy = data.data;
}
}
ngOnInit(): void {
this.subscriptions.add(
this.getService
.getSomeData('someurl')
.subscribe(
data => this.componentCopyLoaded(data), <-ERROR HERE
error => this.componentCopyLoaded(error)
)
);
}
The error message reads:
> Argument of type '{ status: string; data: {}; }' is not assignable to
> parameter of type '{ status: string; data: IComponentData; }'. Types
> of property 'data' are incompatible. Property 'total' is missing in
> type '{}' but required in type 'IComponentData'.ts(2345)
While making the interface properties optional would resolve the errors, using "any" is also an option.
I have attempted to use generics or extension, but I'm struggling to make it work. Any tips on how to resolve this?
For example:
componentCopyLoaded<T>(data: { status: string; data: T }) <- does this make the data generic?
Simple example
export interface IDataInterface {
total: number;
}
data: IDataInterface;
dataReturned(data: IDataInterface): void {
this.data = data;
}
sendData() {
// I want to put an object in with any kind of data structure
// Pretend this is a general service that does an api call to anywhere.
this.dataReturned({total: 1}); <-- this works, sometimes data is this
this.dataReturned({}); <-- this does not, sometimes data is this
}
How it was fixed. Thanks to joshvito pointing me in the right direction.
The error was as shown in the image https://i.sstatic.net/UNTmA.png
And the solution is shown in this image
https://i.sstatic.net/I17TT.png
To address the error in the simple example, I added the following
dataReturned(data: unknown): void { <-- add unknown
this.data = data as IComponentData; <-- this line removed the Type error
}
sendData() {
this.dataReturned({total: 1});
this.dataReturned({});
}