0

我正在使用Reactand immutable.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而不是稳定版本,包括类型。

4

0 回答 0