Been racking my brain for hours on this, basically, I have a bunch of different types defined like this:
export type SharedAPIProps = {
id: string;
};
export type ButtonAPIProps = SharedAPIProps & {
type: "paragraph--button";
field_title: string;
};
export type SlideAPIProps = SharedAPIProps & {
type: "paragraph--slide";
field_slides: []
};
export type allAvailableComponents = ButtonAPIProps | SlideAPIProps;
export type ButtonProps = {
title: string;
}
export type SlideProps = {
slides: [];
}
export type allCleanedProps = ButtonProps | SlideProps;
Then I have a function to convert an API response to a clean version:
export const toCleanProps = (component: allAvailableComponents): allCleanedProps => {
const { type } = component;
const convertedProps: allCleanedProps = {} as allCleanedProps;
switch (type) {
case "paragraph--button":
convertedProps.title = component.field_title;
break;
case "paragraph--slide":
convertedProps.slides = component.field_slides;
break;
}
return convertedProps;
}
The issue is I'm getting Typescript errors on every property of the convertedProps. When I have just a single type defined in allComponentProps like:
export type allAvailableComponents = ButtonAPIProps;
I don't get the errors on the paragraph--button convertedProps properties, but of course do on the paragraph--slide convertedProps properties.
New to Typescript, so bear with me, I'm probably missing something simple here and tried a bunch of different things, but none work.
Error message being those props don't exist on the defined types.
The fundamental issue is that narrowing the type of component doesn't narrow the type of convertedProps, so TypeScript doesn't know that the assignments are okay.
You can fix it by creating componentProps in the branches:
export const toCleanProps = (component: allAvailableComponents): allCleanedProps => {
const { type } = component;
let convertedProps: allCleanedProps;
switch (type) {
case "paragraph--button":
convertedProps = {
title: component.field_title,
};
break;
case "paragraph--slide":
convertedProps = {
slides: component.field_slides,
};
break;
default:
throw new Error(`Unexpected 'type'`);
}
return convertedProps;
}
If the cleanup process is involved, you could split it off into helper functions:
const cleanButtonProps = (component: ButtonAPIProps): ButtonProps => {
return {
title: component.field_title,
};
};
const cleanSlideProps = (component: SlideAPIProps): SlideProps => {
return {
slides: component.field_slides,
};
};
export const toCleanProps = (component: allAvailableComponents): allCleanedProps => {
const { type } = component;
let convertedProps: allCleanedProps;
switch (type) {
case "paragraph--button":
convertedProps = cleanButtonProps(component);
break;
case "paragraph--slide":
convertedProps = cleanSlideProps(component);
break;
default:
throw new Error(`Unexpected 'type'`);
}
return convertedProps;
}