在Javascript中使用泛型的高阶类?

时间:2018-01-31 02:53:33

标签: javascript typescript react-native generics flowtype

我想知道是否有一种正确的方法来包装类似于React Native中的更高阶组件的类?我有以下内容:

const RecyclerViewDataWrap = <P>(Wrapee: Class<React$Component<P, *>>) => {
  return class {
    props: P

    constructor(props: P){
      this.props = props
    }
    render(){
      return (
        <Wrapee {... this.props}  />
      )
    }
  }
}

export default RecyclerViewDataWrap

// in some other component file:
export const SomeComponentData = RecyclerViewDataWrap(SomeComponent)

这允许我创建SomeComponentData个对象,这些对象将使用我告诉它的道具呈现SomeComponents。但是,我希望能够声明泛型类型,以便构造函数可以知道它想要的类型。理想情况下,我想做这样的事情:

type Props = {
  title?: string,
  price?: number,
}
export const SomeComponentData = RecyclerViewDataWrap<Props>(SomeComponent)

1 个答案:

答案 0 :(得分:1)

我有点(我使用类Props而不是类型):

说你有

class SomeComponent {
    constructor(public name: string) {
    }
}

class Props {
    title?: string;
    price?: number;
}

然后你可以这样做:

type Constructor<T> = new(...args: any[]) => T;

function RecyclerViewDataWrap<P, T extends Constructor<{}>>(Props: new ()=> P, Base: T) {

    return class extends Base {
        props: P = new Props();

        constructor(...args: any[]) {
            super(...args);
        }
    }
}

const SomeComponentData = RecyclerViewDataWrap(Props, SomeComponent);


let componentData = new SomeComponentData("My Component");
componentData.props.title = 'My title';

console.log(componentData);

我这主要基于https://github.com/Microsoft/TypeScript/wiki/What%27s-new-in-TypeScript#support-for-mix-in-classesTypescript instantiate generic object

也许@cartant可以验证这一点,因为他似乎更了解这些东西。