泛型推断

  1. export interface UUIDProps {
  2. uuid: string
  3. }
  4. export function withUUID<P extends UUIDProps>(
  5. Compt: React.ComponentType<P>
  6. ): React.FC<Partial<UUIDProps> & Omit<P, keyof UUIDProps>> {
  7. const _withUUID: React.FC<Partial<UUIDProps> & Omit<P, keyof UUIDProps>> = (props) => {
  8. const { uuid: propsUuid, ...propsWithoutUUID } = props
  9. const [uuid, setUUID] = React.useState(propsUuid)
  10. React.useEffect(() => {
  11. if (!uuid) setUUID('')
  12. }, [uuid])
  13. if (!uuid) {
  14. return null
  15. }
  16. const _props = { ...propsWithoutUUID, uuid } as P
  17. return <Compt {..._props} />
  18. }
  19. return _withUUID
  20. }
  21. // 被withUUID包装之后,会被传递一个uuiid的属性
  22. const test: React.FC = (props) => {
  23. return <h1>123</h1>
  24. }
  25. const result = withUUID(test) // 这里为什么不报错,因为test组件默认的P是一个{},不满足UUIDProps接口