我为此绞尽脑汁了好几个小时,基本上,我有一堆不同的类型定义如下:
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;
然后我有一个函数可以将 API 响应转换为干净的版本:
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;
}
问题是我在convertedProps
. 当我只定义了一个类型时allComponentProps
:
export type allAvailableComponents = ButtonAPIProps;
我没有得到paragraph--button
convertedProps
属性上的错误,但当然会出现属性上的错误paragraph--slide
convertedProps
。
Typescript 的新手,所以请耐心等待,我可能在这里遗漏了一些简单的东西并尝试了很多不同的东西,但都没有奏效。
错误消息是这些道具在定义的类型上不存在。
根本问题是缩小 of 的类型component
并不会缩小 of 的类型convertedProps
,因此 TypeScript 不知道赋值是否正常。
componentProps
您可以通过在分支中创建来修复它:
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;
}
如果涉及清理过程,您可以将其拆分为辅助函数:
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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句