我已经将我的Props接口划分为一个基接口和两个联合类型:
interface BaseProps {
...
}
interface ControlledInput extends BaseProps {
value: string;
onChange: ...;
}
interface UncontrolledInput extends BaseProps {
defaultValue: string;
ref: string;
}
export const TextInput:
React.SFC<ControlledInput | UncontrolledInput> = ({
type,
label,
value,
...rest
}) => {
但是,解构值给了我一个数组,因为它在UncontrolledInputProps上不存在。
我想我需要一个typeguard,就像这样:
if (typeof rest.value === 'string') {
我真的不能完全理解它。如有任何帮助,我们不胜感激!
发布于 2018-06-03 07:27:39
在官方文档中找到了答案:http://www.typescriptlang.org/docs/handbook/advanced-types.html
因此,要编写的typeguard如下所示:
export function isControlled(input: ITextInputControlledProps |
ITextInputUncontrolledProps):
input is ITextInputControlledProps {
return (input as ITextInputControlledProps).value !== undefined;
}
然后在我的组件中,我可以这样做:
if (isControlled(rest)) {
const { value, onChange } = rest;
valueProps = { value, onChange };
} else {
const { defaultValue, ref } = rest as ITextInputUncontrolledProps;
valueProps = { defaultValue, ref };
}
https://stackoverflow.com/questions/50661860
复制相似问题