我的Props接口分为基本接口和两种Union类型:
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中不存在。
我估计我需要一个打字机,比如:
if (typeof rest.value === 'string') {
我无法真正地绕过它。任何帮助表示赞赏!
答案 0 :(得分:0)
在官方文档上找到答案: http://www.typescriptlang.org/docs/handbook/advanced-types.html
所以要写的打字机看起来如下:
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 };
}