我有一个组件,它接受如下参数:
interface Props {
label: string;
children?: React.ReactNode;
withoutActions?: boolean;
fieldKey?: KeyProperties;
corporate: Corporate;
}表单使用withoutActions和fieldKey。如果withoutActions道具是true,那么就不应该提供fieldKey。
但是,如果我的withoutActions是未定义的,那么我应该强制执行fieldLabel类型为**KeyProperties**,这是它的可用值的特定列表。
如果withoutActions是未定义的,则如果withoutActions是真的,则不应该定义另一个,而另一个应该按照特定的keyProperties类型来定义。
我怎样才能实现这一点?
发布于 2022-01-15 10:13:02
类似于另一个答案,但您可以稍微重构一下,以便更干净一些。如果withoutActions是false而不是true或undefined,您没有指定预期的行为是什么。在这里,我假设false和undefined的行为是相同的。如果false不是有效类型,您可以像其他答案一样将withoutActions?: false替换为withoutActions: undefined。
type Props = {
label: string;
children?: React.ReactNode;
corporate: Corporate;
} & (
{
withoutActions: true;
} |
{
withoutActions?: false;
fieldKey: KeyProperties;
}
)然而,这里有一个重要的陷阱,你应该意识到。由于类型记录的结构类型,您只有在直接分配对象文字时才会得到过多的属性检查。当将对象赋值为推断类型时,不会得到多余的属性检查。TypeScript和React对待直接道具声明就像对待对象文本一样,并且会像您所希望的那样进行过多的属性检查。但是,在某些情况下,如果将对象赋值给变量并让它们的类型被推断,TypeScript可能不会警告存在多余的属性。
看看此演示基于您最初的示例。示例1和例2会因为过多的属性检查而出错,但示例3不会。
const ExampleOne = () => {
// Type error - excess property checking
return <Component label={''} corporate={''} withoutActions fieldKey={''} />;
}
const ExampleTwo = () => {
const props: Props = {
label: '',
corporate: '',
withoutActions: true,
// Type error - excess property checking
fieldKey: '',
}
return <Component {...props} />;
}
const ExampleThree = () => {
const props = {
label: '',
corporate: '',
withoutActions: true,
fieldKey: '',
}
// No type error - no excess property checking
return <Component {...props} />;
}发布于 2022-01-13 18:13:35
我没有完全理解您的需求,但是我会使用类型别名而不是接口。例如,类似这样的事情:
type Props = {
label: string,
children?: React.ReactNode,
withoutActions: true,
corporate: Corporate
} | {
label: string,
children?: React.ReactNode,
withoutActions: undefined,
fieldKey: KeyProperties,
corporate: Corporate
}https://stackoverflow.com/questions/70700562
复制相似问题