'constructor parameter type as optional lookup property
i've just started creating constructors based on my interfaces and i'm stuck here, where "Property 'message' does not exist on type '{ message: string; } | undefined'" in the errorMessage parameter's lookup type:
interface fetchResponse {
data:null|object|any[];
error?:{
message:string;
};
};
interface FetchResponse extends fetchResponse {};
class FetchResponse {
constructor(data:fetchResponse["data"], errorMessage?:fetchResponse["error"]["message"]) {
this.data = data;
this.error = errorMessage ? {
message: errorMessage,
} : undefined;
};
};
i found the following possible ways to fix this, but i've been able to successfully implement none:
- resolving the property of
errorbased on the property ofdata(i.e ifdatais an object/array thenerroris undefined, and ifdatais null thenerroranderror.messageare defined), which should make it so thaterroris not possibly undefined if i'm trying to pass anerrorMessage: the only way i found to maybe do that is with a union (according to this SO post), but imitating that as seen below only caused typescript to flag 2 more problems which i'm clueless about in the latter half of the code
interface fetchResponsePositive {
data:object|any[];
};
interface fetchResponseNegative {
data:null;
error: {
message:string;
};
};
type fetchResponse = fetchResponsePositive | fetchResponseNegative;
overloading (according to this OS post)? this is my first ever exposure to the concept of overloading, after looking it up i understand the concept but cant figure out how to implement it here in a way that solves the issue (or whether it's even a solution to this)
adding a definite assertion to the
fetchResponse["error"]["message"]lookup: i just have no idea how to do that, i placed the exclamation mark in every conceivable spot to no success
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
