New to react typescript and I have been getting below typescript error while creating components:
interface APIResponseA {
a:string[];
b:number;
c: string | null; // <-
}
interface APIResponseB {
a:string[] | null;
b:number;
d:number; // <-
e:string; // <-
}
interface IProps {
details: APIResponseA | APIResponseB;
}
...
const values: IValues = {
a:props.details.a || [];
b:props.details.b || 0;
c:props.details?.c || ""; // <- ts error
d:props.details?.d || 0; // <- ts error
e:props.details?.e || ""; // <- ts error
}
getting error for c, d, e
Property 'd' does not exist on type 'APIResponseA | APIResponseB'.
Property 'd' does not exist on type 'APIResponseA'.ts(2339)
Trying to reuse the component so need it to be dynamic.
The issue seems like here details: APIResponseA | APIResponseB;
but not sure how to correctly set the type. Please help?
Adding some context:
This component is a form (using formik) in which the initial values are populated from API responses. Basically it’s the same form but for different pages the API response varies.
2
Answers
This is expected as the
details
property is the union ofResponseA
andResponseB
. So typescript can only guarentee the types that are both inResponseA
andResponseB
.You can use the
in
operator in typescript to narrow it’s type. You can do something like this. Take a look at this typescript playgroundWell it’s hard to know what’s the best solution without knowing the context.
Typically you will transform the response of those APIs to a data type that fit into a component. It seems like your component is just the representation of those data. So this is how I will do in this case:
APIResponseA | APIResponseB
will result an interface that has noc
,d
,e
fields.