[英]Typescript how to include types conditionally?
我有一个案例,我需要有条件地在 Typescript 中包含类型。 我不是 100% 确定它是否可能使用 Typescript。
我在下面的示例中简化了代码。
type FlexBoxType = {
inline?: boolean;
justifyContent?: string;
alignItems?: string;
/* and so on */
}
type FlexItemType = {
box?: boolean;
flex?: string|number;
shrink?: string | number;
/* and so on */
}
type FlexItemProps =
| FlexItemType & { box: true } & FlexBoxType
| FlexItemType;
const flexItemStylesGenerator = (args: FlexItemProps) => {
/* function to generate flex-item styles */
if(args.box) {
/* args includes props of FlexBoxType and FlexItemType */
}
else {
/* args includes props of FlexItemType only */
}
};
我创建了一个 function flexItemStylesGenerator
生成 CSS styles 使用传递的 ZDBEZ6FB4CAA5BDA9FEDDA7 如果box属性为真,那么用户可以指定FlexItemType
以及FlexBoxType
,否则只能指定FlexItemType
。
但是,上述类型没有按预期工作
flexItemStylesGenerator({ flex: 1 }); // works properly, as expected
flexItemStylesGenerator({ jusifyContent: 'space-between' }); // gives warning, as expected cannot use FlexBoxType prop without passing box: true.
flexItemStylesGenerator({ flex: 1, justifyContent: 'space-between' }); // no warning, unexpected
那么如何声明FlexItemProps
类型,以便用户只能在box属性设置为 true 时传递FlexBoxType
?
您应该将never
类型添加到独占类型。
type Never<T> = {[P in keyof T]?: never}
type FlexItemProps =
| FlexItemType & { box: true } & FlexBoxType
| FlexItemType & Never<FlexBoxType>
never
类型将选择退出类型保护。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.