【发布时间】:2020-04-14 13:51:36
【问题描述】:
我的代码中有两个接口,我想在这两者之间选择一种类型。
接口代码如下:
interface createUserToSiteMutateUseStates {
setStateId: (value: React.SetStateAction<string | null | undefined>) => void;
StateId: string | null | undefined;
setCityId: (value: React.SetStateAction<string | null | undefined>) => void;
}
interface updateStoreSpatialCommitmentsVariablesUseState {
setStateSelected: (
value: React.SetStateAction<SelectorOptions[] | undefined | null>
) => void;
}
我创建了一个类型来识别真正的接口:
type whichType<T> = T extends "createUserToSiteMutate"
? createUserToSiteMutateUseStates
: T extends "updateStoreSpatialCommitmentsVariables"
? updateStoreSpatialCommitmentsVariablesUseState
: null;
最后我使用了whichType:
export interface Props {
type:
| "createUserToSiteMutate"
| "createUnitVariables"
| "updateStoreSpatialCommitmentsVariables";
useStateProps?: whichType<type>;
}
但是当我使用Props 时,我得到了这个错误:
const handleChange = (option: SelectorOptions) => {
switch (type) {
case "createUserToSiteMutate":
useStateProps!.setCityId && useStateProps!.setCityId(null);
useStateProps!.setUniversityId &&
useStateProps!.setUniversityId(null);
useStateProps!.setOrganizationId &&
useStateProps!.setOrganizationId(null);
useStateProps!.setUnitId && useStateProps!.setUnitId(null);
useStateProps!.setStateId && useStateProps!.setStateId(option.value);
default:
break;
}
};
“createUserToSiteMutateUseStates”类型上不存在属性“setCityId”| updateStoreSpatialCommitmentsVariablesUseState'。
“updateStoreSpatialCommitmentsVariablesUseState”类型上不存在属性“setCityId”。ts(2339)
如何解决此错误? whichType有问题吗?
【问题讨论】:
-
updateStoreSpatialCommitmentsVariablesUseState 中没有 setCityId 但我收到此错误。
-
请考虑将此处的代码编辑为真正的minimal reproducible example,如How to Ask 中所述。现在有很多错误似乎与您的问题无关。如果有人将代码放入独立的 IDE 中,他们应该能够重现您的特定问题,而无需花时间尝试修复或选择性地忽略其他问题。
标签: javascript reactjs typescript typechecking