基于prop在React组件中创建泛型类

时间:2018-07-13 10:38:44

标签: reactjs typescript immutable.js typescript-generics

我正在使用Reactimmutable.js,并且我需要在组件内部使用基于Record的类型,它们的字段值之一为keyof一些物体。

这是基本的类型定义:

import { Record } from 'immutable';

export const types = { // basic object holding possible values for Record
  date: 'date'
};

export interface IProp<T> { // interface for Record
  type: keyof T | '';
}

export type PropertyFactory<T extends typeof types> = typeof Property;
export function Property<T extends typeof types>(types: T) {
    return class CustomProperty extends Record<IProp<T>>({type: ''}) {};
}

在另一个地方,我指的是这种类型以获得派生的类型:

export const derivedTypes = Object.assign({}, types, {
  select: 'select'
});

export class DerivedProperty extends Property(derivedTypes) {}

最后,我创建了React元素本身:

interface Props<T extends typeof types, P> {
  types: T;
  ctor: { new(js?: Partial<IProp<T>>): P };
}

class Element<T extends typeof types, P extends InstanceType<ReturnType<PropertyFactory<T>>>> extends React.Component<Props<T, P>> {
  constructor(props: Props<T, P>){ super(props) };
  create() {return new this.props.ctor()};
}

const test = <Element<typeof derivedTypes, DerivedProperty>
  types={derivedTypes}
  ctor={DerivedProperty}
/>

它会引发编译错误:

Type 'DerivedProperty' does not satisfy the constraint 'Property<{ date: string; }>.CustomProperty'.
  Types of property 'toJSON' are incompatible.
    Type '() => IProp<{ date: string; } & { select: string; }>' is not assignable to type '() => IProp<{ date: string; }>'.
      Type 'IProp<{ date: string; } & { select: string; }>' is not assignable to type 'IProp<{ date: string; }>'.
        Type '{ date: string; }' is not assignable to type '{ date: string; } & { select: string; }'.
          Type '{ date: string; }' is not assignable to type '{ select: string; }'.
            Property 'select' is missing in type '{ date: string; }'.

我不太清楚发生了什么问题,但是无论是使用Element的类型推断还是使用显式泛型,都可以。也许我走错了路?


更新::我们使用的是immutable.js v4.0.0-rc.9,而不是不是稳定版,其中包括键入内容。

0 个答案:

没有答案
相关问题