【发布时间】:2021-06-14 14:19:27
【问题描述】:
目前我在打字稿方面遇到了一些麻烦。
当multiSelect 为真时,我有一个 React 组件,其中一些打字稿定义应该更改。当multiSelect 为真或假时,onUpdate 和value 将被强制为字符串 OR string[]。但它不起作用。
export interface DefaultUserTypeFieldProps {
className?: string;
disabled?: boolean;
/**
* The label of the input
*/
label?: string;
autoSelectUserId?: string;
}
export interface SingleUserTypeFieldProps extends DefaultUserTypeFieldProps {
multiSelect: false;
value: string;
onUpdate: (value: string, isValid: boolean) => void;
}
export interface MultipleUserTypeFieldProp extends DefaultUserTypeFieldProps {
multiSelect: true;
value: string[];
onUpdate: (value: string[], isValid: boolean) => void;
}
export type UserTypeFieldProps = SingleUserTypeFieldProps | MultipleUserTypeFieldProp;
React 组件如下所示
export const UserTypeField = (props: UserTypeFieldProps) => {
const {
className,
label,
disabled,
value,
autoSelectUserId,
multiSelect = false,
onUpdate,
} = props;
const handleSelectUser = (selectedUserIds: string[]) => {
close();
if (multiSelect) {
onUpdate(selectedUserIds, true);
} else {
onUpdate(selectedUserIds[0], true);
}
};
return ...;
};
在handleSelectUser 中,我收到错误TS2345: Argument of type 'string' is not assignable to parameter of type 'string & string[]'. Type 'string' is not assignable to type 'string[]'.。如您所见,它与 & 连接,但在接口定义中您可以看到我使用带有 | 的条件类型。
你有什么想法吗?
感谢您的帮助!
【问题讨论】:
-
只需使用
as。喜欢onUpdate(selectedUserIds as string[])
标签: reactjs typescript typescript-typings react-typescript conditional-types