泛型推断
export interface UUIDProps {
uuid: string
}
export function withUUID<P extends UUIDProps>(
Compt: React.ComponentType<P>
): React.FC<Partial<UUIDProps> & Omit<P, keyof UUIDProps>> {
const _withUUID: React.FC<Partial<UUIDProps> & Omit<P, keyof UUIDProps>> = (props) => {
const { uuid: propsUuid, ...propsWithoutUUID } = props
const [uuid, setUUID] = React.useState(propsUuid)
React.useEffect(() => {
if (!uuid) setUUID('')
}, [uuid])
if (!uuid) {
return null
}
const _props = { ...propsWithoutUUID, uuid } as P
return <Compt {..._props} />
}
return _withUUID
}
// 被withUUID包装之后,会被传递一个uuiid的属性
const test: React.FC = (props) => {
return <h1>123</h1>
}
const result = withUUID(test) // 这里为什么不报错,因为test组件默认的P是一个{},不满足UUIDProps接口