参数 isNested
和 typography
都是可选的,但我想强制,如果用户没有将 isNested
设置为 true
那么 typography
必须是定义。
有没有办法让 Typescript 知道我正在检查是否通过抛出错误传递了 prop isNested
或 typography
?
如果两者都没有定义,我就会抛出一个错误(Prop "typography" must be defined when Text isn't nested!
),因此我知道在我下面的代码中,必须定义 isNested
或 typography
,但 Typescript 不理解它,我必须通过以下方式仔细检查:
!isNested && typography && generateTypographyStyles(theme, typography)
代替:
!isNested && generateTypographyStyles(theme, typography)
否则会抛出错误:Type 'undefined' is not assignable to type 'Typography'.
const generateTextStyles = ({
align,
color,
isNested,
typography,
}: {
align?: Align;
color?: Theme.Color;
isNested?: boolean;
typography?: Theme.Typography;
}): FlattenInterpolation<ThemeProps<DefaultTheme>> => {
if (!isNested && !typography) {
throw new Error(
'Prop "typography" must be defined when Text isn\'t nested!'
);
}
return css(
({ theme }) => css`
${!isNested && typography && generateTypographyStyles(theme, typography)};
color: ${color && getColor(theme, color)};
text-align: ${align || undefined};
`
);
};
有没有更好的方法来处理这种情况?